【问题标题】:Pandas column expressions with if else带有 if else 的 Pandas 列表达式
【发布时间】:2014-09-02 15:04:57
【问题描述】:

我正在以这种方式在 Python pandas 中创建一个字符串表达式

df['ABC'] = (df['A']
                  + ' + ' + df['B']
                  + ' + ' + df['C'])

但是,pandas 返回此错误

TypeError: cannot concatenate 'str' and 'float' objects

数据框有几列有NaN,并且在这些情况下字符串连接失败。对于测试用例,我如何编写语句来实现连接,如下所示。看来我们必须在上面的表达式中添加一条 ifelse 语句:

A   B   C   ABC
x           x
x   y       x + y
x   y   z   x + y + z

【问题讨论】:

    标签: string python-2.7 pandas concatenation


    【解决方案1】:

    你可以这样做:

    >>> join_row = lambda ts: ' + '.join(ts.dropna())
    >>> df[['A', 'B', 'C']].apply(join_row, axis=1)
    0            x
    1        x + y
    2    x + y + z
    dtype: object
    

    [['A', 'B', 'C']] 仅当数据框中还有其他列时才需要。

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多