python - 使用 NaN 值迭代连接 pandas 中的列

标签 python pandas

我有一个 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 中的 NaN 值.loc[1, "y"] 搞乱了连接。最终,由于这个空值,整个 1st 行在 df["concat"] 中以 NaN 结束。我该如何解决这个问题?我需要指定 pd.Series.str.cat 的某些选项吗?

最佳答案

选项 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

关于python - 使用 NaN 值迭代连接 pandas 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277838/

相关文章:

python - 在字符串中查找插入

python - 使用 xerr 和 yerr 使用 matplotlib 的散点图

python - 使用 Django 的 manage.py 命令运行 C​​elery 时,返回一个奇怪的错误

Python 导入包 gpiosimulator 失败

python - pandas 一个热编码数据的每种列组合的行数

python - 如何尽快将所有数据分组?

python - 匹配 python 数据集中的多个项目

python - 错误 : Found array with dim 3. 预期估计器 <= 2

python - 绘制时间戳数据帧的图表

python(pandas)在数据帧内合并,无需for循环