【问题标题】:concatenate multiple columns based on index in pandas根据熊猫中的索引连接多个列
【发布时间】:2012-08-19 22:06:01
【问题描述】:

作为this post 的后续行动,我想根据它们的索引连接一些列,但我遇到了一些问题。在此示例中,我收到与 map 函数相关的属性错误。解决此错误的帮助以及对列进行等效连接的代码将不胜感激。

    #data
    df = DataFrame({'A':['a','b','c'], 'B':['d','e','f'], 'C':['concat','me','yo'], 'D':['me','too','tambien']})

    #row function to concat rows with index greater than 2
    def cnc(row):
        temp = []
        for x in range(2,(len(row))):
            if row[x] != None:
                temp.append(row[x])
        return map(concat, temp)

    #apply function per row
    new = df.apply(cnc,axis=1)

    #Expected Output
    new

    concat me
    me too
    yo tambien

谢谢, 扎克cp

【问题讨论】:

  • 请发布您收到的错误以及您的预期输出。
  • @BrenBarn。完成,谢谢。

标签: python pandas


【解决方案1】:

这样的事情怎么样?

>>> from pandas import *
>>> df = DataFrame({'A':['a','b','c'], 'B':['d','e','f'], 'C':['concat','me','yo'], 'D':['me','too','tambien']})
>>> df
   A  B       C        D
0  a  d  concat       me
1  b  e      me      too
2  c  f      yo  tambien
>>> df.columns[2:]
Index([C, D], dtype=object)
>>> df[df.columns[2:]]
        C        D
0  concat       me
1      me      too
2      yo  tambien
>>> [' '.join(row) for row in df[df.columns[2:]].values]
['concat me', 'me too', 'yo tambien']
>>> df["new"] = [' '.join(row) for row in df[df.columns[2:]].values]
>>> df
   A  B       C        D         new
0  a  d  concat       me   concat me
1  b  e      me      too      me too
2  c  f      yo  tambien  yo tambien

如果你有 None 对象漂浮在周围,你也可以处理它。例如:

>>> df["C"][1] = None
>>> df
   A  B       C        D
0  a  d  concat       me
1  b  e    None      too
2  c  f      yo  tambien
>>> rows = df[df.columns[2:]].values

接近英语:

>>> new = [' '.join(word for word in row if word is not None) for row in rows]
>>> new
['concat me', 'too', 'yo tambien']

使用filter

>>> new = [' '.join(filter(None, row)) for row in rows]
>>> new
['concat me', 'too', 'yo tambien']

等等。您可以在一行中完成,但我认为将其分开更清楚。

【讨论】:

  • 你也可以使用列表推导消除 None 值吗?
  • 请注意,Python 3 中停止支持filter(None, iterable),需要在filter(bool, iterable) 那里做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多