【发布时间】:2017-10-09 10:19:46
【问题描述】:
我有一个 Python Pandas 数据框 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 中的值的 list。所以它看起来像这样:
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)
如果我只想要 3 列,则返回这是完美的:
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]
我完全不知道为什么请求由数据框中的所有列组成“组合”列表会产生错误,但是选择除 1 列之外的所有列来创建“组合”列表并且列表创建为预期的。
【问题讨论】:
-
我仍然很困惑为什么你的方法不起作用
-
一定是个bug
标签: python list pandas lambda apply