【问题标题】:Pandas - combine column values into a list in a new columnPandas - 将列值组合到新列中的列表中
【发布时间】: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

我正在尝试创建一个新列,它是 ABCD 中的值的 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


【解决方案1】:

试试这个:

t['combined']= t.values.tolist()

t
Out[50]: 
         A         B     C        D                       combined
0    hello         1  GOOD  long.kw      [hello, 1, GOOD, long.kw]
1     1.20  chipotle   NaN    bingo    [1.2, chipotle, nan, bingo]
2  various       NaN  3000   123.46  [various, nan, 3000, 123.456]

【讨论】:

  • 如果我是正确的,t.values 是没有标题的数据帧的 numpy 数组表示。 Numpy 数组有成员 tolist() 来返回一个(可能是嵌套的)列表。
  • 你是对的,但是@clg4 方法应该可以工作,这可能是一个错误
  • 有没有办法在每一行中获取 nan 值?
  • 如果您不想合并所有其他列而只想合并子集怎么办?
  • @pedjjj t[cols].values.tolist()
猜你喜欢
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2019-11-29
相关资源
最近更新 更多