gpt4 book ai didi

python - 两列相加

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:23 26 4
gpt4 key购买 nike

假设这是我的 df 我正在寻找一种将一列与另一列相加的方法。例如:除了 "col a" 其他所有东西都应该相互添加colb + colc、cold + cole、colf + colg、colh + coli

        a       b    c      d       e       f      g       h        i
group
A 0.15 0.1 0.1 0.15 0.15 0.1 0.1 0.10 0.05
B 0.13 NaN NaN NaN 0.40 0.2 NaN 0.13 0.06

期望的输出:

          a      b      d        f      h    
group
A 0.15 0.2 0.30 0.2 0.15
B 0.13 NaN 0.40 0.2 0.19

我知道我可以手动添加两列,但我正在寻找更简单的方法或应用函数来实现输出。

我想不出办法。有帮助吗?

最佳答案

使用addshift ed DataFrameiloc 没有选择第一列或通过 drop 删除,最后按列名列表过滤:

cols = ['a','b','d','f','h']
df = df.add(df.iloc[:, 1:].shift(-1,axis=1), fill_value=0)[cols]

备选方案:

df = df.add(df.drop('a', axis=1).shift(-1,axis=1), fill_value=0)[cols]

print (df)
a b d f h
group
A 0.15 0.2 0.3 0.2 0.15
B 0.13 NaN 0.4 0.2 0.19

关于python - 两列相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52361048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com