Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 串联多个变量在迭代内部不起作用,在迭代外部起作用_Python_Python 3.x_Pandas_Concatenation - Fatal编程技术网

Python 串联多个变量在迭代内部不起作用,在迭代外部起作用

Python 串联多个变量在迭代内部不起作用,在迭代外部起作用,python,python-3.x,pandas,concatenation,Python,Python 3.x,Pandas,Concatenation,我正在尝试连接几个变量并计算总和,因为我想做多个操作,我正在迭代所有可能的变量组合,这些变量已经保存在df.cols中,但我得到了key error 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

我正在尝试连接几个变量并计算总和,因为我想做多个操作,我正在迭代所有可能的变量组合,这些变量已经保存在df.cols中,但我得到了key error

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]"
例如,当我尝试打印时,我:

print(i)
['D120_1', 'Y69_0', 'K189_0']
当我在没有迭代的情况下尝试使用['D120_1','Y69_0','K189_0']替换I时,效果很好。为什么它在迭代内部识别密钥,而在迭代外部不识别密钥

df1["col1"] = df1.loc[:, ['D120_1', 'Y69_0', 'K189_0']].sum(axis = 1)
虽然这与迭代中的情况相同,但效果很好

df1["col1"] = df1.loc[:, ['D120_1', 'Y69_0', 'K189_0']].sum(axis = 1)
但这不起作用:

df1["col1"] = df1.loc[:, i].sum(axis = 1)

如果在Pandas中没有记错的话,那么开始索引和停止索引都包含在切片中,而Python在跳过最后一个索引时是这样做的。看看这是否是问题的根源-您可能正在迭代一个不可用的索引(标签)。

事实上,我发现列表保存为字符串“['D120_1'、'Y69_0'、'K189_0']”

为了解决我使用的问题


我不确定我的变量是否会是一个列表。Try df1[name]=df1.loc[:,list(i)].sum(axis=1)