【问题标题】:Combining two columns give ValueError: Wrong number of items passed 2, placement implies 1结合两列给出 ValueError: Wrong number of items passed 2, placement 意味着 1
【发布时间】:2018-03-14 04:34:43
【问题描述】:

我有一个简单的数据框:

import pandas as pd
d = pd.DataFrame({'a':[[1], [2], [3]], 'b': [[4], [5], [6]]}) 
print d
  a    b
  0  [1]  [4]
  1  [2]  [5]
  2  [3]  [6]

我想得到

  combined
 0   [1, 4]
 1   [2, 5]
 2   [3, 6]

我用了以下

d['combined'] = d.apply(lambda row: row.a + row.b, axis=1)

它给了我错误:

ValueError: Wrong number of items passed 2, placement implies 1

为什么会

d['combined'] = d.apply(lambda row: row.a[0] + row.b[0], axis=1)

可以工作(虽然不是我需要的),但我上面的代码出错了?

更新:

其实我原来的代码更像这样:

d = pd.DataFrame({'a':[[1, 2], [2, 3], [3, 4]], 'b': [[4, 5], [5, 6], [6, 7]]}) 
        a       b
0  [1, 2]  [4, 5]
1  [2, 3]  [5, 6]
2  [3, 4]  [6, 7]

我想将列表中a的第一个元素和b中的最后一个元素作为

     combined
0    [1, 5]
1    [2, 6]
2    [3, 7]

似乎我可以先用空字符串创建一个新列,然后使用 apply 来修改它,正如下面的答案之一所指出的那样,直接添加列不会让我灵活地操作列表。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    先创建一个空白系列名称“组合”作为列,我不知道为什么ValueError: Wrong number of items passed - Meaning and suggestions?

    import pandas as pd
    d = pd.DataFrame({'a':[[1], [2], [3]], 'b': [[4], [5], [6]]})
    d['combined'] = ''
    d['combined'] = d.apply(lambda row: row.a + row.b, axis=1)
    

    【讨论】:

      【解决方案2】:

      你不需要使用申请这个:

      d['c'] = d.a + d.b
      
          a    b    c
      0  [1]  [4]  [1, 4]  
      1  [2]  [5]  [2, 5]  
      2  [3]  [6]  [3, 6]
      

      【讨论】:

      • 谢谢!没想到这么简单。
      【解决方案3】:

      一个简单的 d.sum(1) 工作

      d['combined'] = d.sum(1)
      
          a   b   combined
      0   [1] [4] [1, 4]
      1   [2] [5] [2, 5]
      2   [3] [6] [3, 6]
      

      【讨论】:

      • 谢谢,在我的真实数据中我还有其他列,但是这个功能非常简单实用!
      猜你喜欢
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2020-07-24
      相关资源
      最近更新 更多