【发布时间】: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 的选项吗?
【问题讨论】: