【发布时间】:2021-07-12 12:06:21
【问题描述】:
我有以下代码。
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
print(df)
for index, row in df.iterrows():
df['c3'][index] = df['c1'][index] + df['c2'][index]
print(df['c1'][index], df['c2'][index], df['c3'][index])
print(df)
我想要做的是遍历数据框并添加第三列,其中包含其他两列的总和。最终结果应该是这样的。
c1 c2 c3
0 10 100 110
1 11 110 121
2 12 120 132
目前我遇到了问题KeyError: 'c3'
如何实现我想要的?
【问题讨论】:
-
df["c3"] = df.sum(1) -
返回 330、363 和 396。这是错误的。有没有办法像示例中那样指定列?
-
你可以这样做:
df["c3"] = df[["c1", "c2"]].sum(1)
标签: python pandas numpy loops jupyter-notebook