【问题标题】:Pandas combine multiple columns (with NoneType)Pandas 组合多列(使用 NoneType)
【发布时间】:2019-02-16 00:02:44
【问题描述】:

如果之前有人问过/回答过这个问题,我深表歉意,但经过一段时间的搜索,我找不到这个问题的答案。

很简单地说,我想将多个列合并为一个,并用 , 问题是有些单元格是空的(NoneType)

当组合它们时,我得到:

  1. TypeError: ('sequence item 3: expected str instance, NoneType found', '发生在索引 0')

  1. 添加 .map(str) 时,它会为每个 NoneType 值添加“None”(有点预期)

假设我有一个看起来像这样的生产数据框

     0        1        2
1   Rice
2   Beans    Rice
3   Milk     Beans   Rice
4   Sugar    Rice

我想要的是带有值的单列

    Production
1   Rice
2   Beans, Rice
3   Milk, Beans, Rice
4   Sugar, Rice

通过一些搜索和调整,我添加了以下代码:

testColumn = productionFrame.iloc[::].apply(lambda x: ', '.join(x)), axis=1)

这会产生问题 1

或者这样改:

testColumn = productionFrame.iloc[::].apply(lambda x: ', '.join(x.map(str)), axis=1)

这会产生问题 2

也许补充一下我是个新手,现在有点探索 Pandas/Python 是件好事。因此,非常感谢任何帮助或朝着正确方向前进!

【问题讨论】:

  • 如果column 0column 2 有一个值而column 1 没有你想要什么?
  • @J.Doe 在我的 DataFrame 中,值之间不可能有 NoneTypes。但是为了它的发生,我仍然想要相同的最终结果。 "column0, column2" 其中 column1 被省略了,因为它是一个 NoneType。我希望这是有道理的

标签: python pandas dataframe


【解决方案1】:

pd.Series.str.cat 应该在这里工作

df
Out[43]: 
       0      1     2
1   Rice    NaN   NaN
2  Beans   Rice   NaN
3   Milk  Beans  Rice
4  Sugar   Rice   NaN

df.apply(lambda x: x.str.cat(sep=', '), axis=1)
Out[44]: 
1                 Rice
2          Beans, Rice
3    Milk, Beans, Rice
4          Sugar, Rice
dtype: object

【讨论】:

    【解决方案2】:

    您可以在将NaN 值转换为空字符串后使用str.join

    res = df.fillna('').apply(lambda x: ', '.join(filter(None, x)), axis=1)
    
    print(res)
    
    0                 Rice
    1          Beans, Rice
    2    Milk, Beans, Rice
    3          Sugar, Rice
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2020-09-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2012-06-12
      • 1970-01-01
      相关资源
      最近更新 更多