I have a Python Pandas dataframe df:
d = [['hello', 1, 'GOOD', 'long.kw'],
[1.2, 'chipotle', np.nan, 'bingo'],
['various', np.nan, 3000, 123.456]]
t = pd.DataFrame(data=d, columns=['A','B','C','D'])
它看起来像这样:
print(t)
A B C D
0 hello 1 GOOD long.kw
1 1.2 chipotle NaN bingo
2 various NaN 3000 123.456
我正在尝试创建一个新的列,这是由 A
、B
、C
和 D
的值组成的 列表
。因此它应该是这样的:
t['combined']
Out[125]:
0 [hello, 1, GOOD, long.kw]
1 [1.2, chipotle, nan, bingo]
2 [various, nan, 3000, 123.456]
Name: combined, dtype: object
我正在尝试这段代码:
t['combined'] = t.apply(lambda x: list([x['A'],
x['B'],
x['C'],
x['D']]),axis=1)
这会返回以下错误:
ValueError: Wrong number of items passed 4, placement implies 1
我感到困惑的是,如果我删除列表中想要添加的其中一列(或者在数据框中添加另一列,但不将其添加到列表中),我的代码就可以工作。
例如,运行以下代码:
t['combined'] = t.apply(lambda x: list([x['A'],
x['B'],
x['D']]),axis=1)
返回这个内容非常完美,如果我只想要三列的话。
print(t)
A B C D combined
0 hello 1 GOOD long.kw [hello, 1, long.kw]
1 1.2 chipotle NaN bingo [1.2, chipotle, bingo]
2 various NaN 3000 123.456 [various, nan, 123.456]
我完全不明白为什么请求在数据框中的所有列合并成“combined”列表会导致错误,但是选择除一个列外的所有列来创建“combined”列表却能正常工作。