【发布时间】:2017-11-12 20:49:02
【问题描述】:
我正在尝试连接几个变量并计算总和,由于我想做多个操作,我正在遍历已经保存在 df.cols 中的所有可能的变量组合,但我得到了关键错误。
for i in df.cols[0:20]:
k+=1
name = "cat" + str(k)
df1[name] = df1.loc[:, i].sum(axis = 1)
虽然它在列中,但它会给出 KeyError。
KeyError: "the label [['D120_1', 'Y69_0', 'K189_0']] is not in the [columns]"
例如,当我尝试打印 i 时:
print(i)
['D120_1', 'Y69_0', 'K189_0']
当我在不迭代的情况下尝试将 i 替换为 ['D120_1', 'Y69_0', 'K189_0'] 时效果很好。为什么它在迭代内识别key,在迭代外不识别。
虽然与迭代中的相同,但效果很好。
df1["col1"] = df1.loc[:, ['D120_1', 'Y69_0', 'K189_0']].sum(axis = 1)
但这不起作用:
df1["col1"] = df1.loc[:, i].sum(axis = 1)
【问题讨论】:
-
我不确定 i 变量实际上是否会是一个列表。试试 df1[name] = df1.loc[:, list(i)].sum(axis = 1)
标签: python python-3.x pandas concatenation