【问题标题】:Iteratively concatenate columns in pandas with NaN values用 NaN 值迭代连接 pandas 中的列
【发布时间】:2017-10-17 11:17:53
【问题描述】:

我有一个pandas.DataFrame 数据框:

import pandas as pd

df = pd.DataFrame({"x": ["hello there you can go home now", "why should she care", "please sort me appropriately"], 
    "y": [np.nan, "finally we were able to go home", "but what about meeeeeeeeeee"],
    "z": ["", "alright we are going home now", "ok fine shut up already"]})

cols = ["x", "y", "z"]

我想迭代地连接这些列,而不是像这样写:

df["concat"] = df["x"].str.cat(df["y"], sep = " ").str.cat(df["z"], sep = " ")

我知道将三列放在一起似乎微不足道,但我实际上有 30 列。所以,我想做类似的事情:

df["concat"] = df[cols[0]]
for i in range(1, len(cols)):
    df["concat"] = df["concat"].str.cat(df[cols[i]], sep = " ")

现在,最初的 df["concat"] = df[cols[0]] 行工作正常,但是位置 df.loc[1, "y"] 中的 NaN 值会混淆连接。最终,由于这个空值,整个1st 行在df["concat"] 中最终成为NaN。我怎样才能解决这个问题?我需要指定pd.Series.str.cat 的选项吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    选项 1

    pd.Series(df.fillna('').values.tolist()).str.join(' ')
    
    0                    hello there you can go home now  
    1    why should she care finally we were able to go...
    2    please sort me appropriately but what about me...
    dtype: object
    

    选项 2

    df.fillna('').add(' ').sum(1).str.strip()
    
    0                      hello there you can go home now
    1    why should she care finally we were able to go...
    2    please sort me appropriately but what about me...
    dtype: object
    

    【讨论】:

      【解决方案2】:

      选项 3

      In [3061]: df.apply(lambda x: x.str.cat(sep=''), axis=1)
      Out[3061]:
      0                      hello there you can go home now
      1    why should she carefinally we were able to go ...
      2    please sort me appropriatelybut what about mee...
      dtype: object
      

      【讨论】:

        猜你喜欢
        • 2019-11-28
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2020-05-21
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多