我正在尝试连接包含空值的多个字符串列。但结果不显示串联字符串,而只显示第一列。如何忽略包含空值的值?我试图通过替换nan值来处理这个问题,但这无济于事。import pandas as pdimport numpy as npdf = pd.DataFrame({'Addr1':['a','b','c'], 'Addr2':['', 'x', np.nan], 'Addr3':['202', '201', '203']})df1 = pd.DataFrame([])df1['patient address'] = df['Addr1'].astype(str).fillna('',) + " " + df['Addr2'].astype(str).fillna('') + " " + df['Addr3'].astype(str).fillna('') print(df1)预期输出: patient address0 a 2021 b x 2012 c 203
2 回答
jeck猫
TA贡献1909条经验 获得超7个赞
堆栈和 与 on ,默认情况下删除 :groupby+agg.joinlevel=0stack()NaN
df1['patient address'] = df.stack().groupby(level=0).agg(' '.join)
0 a 202
1 b x 201
2 c 203
dtype: object
桃花长相依
TA贡献1860条经验 获得超8个赞
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"Addr1": ["a", "b", "c"],
"Addr2": ["", "x", np.nan],
"Addr3": ["202", "201", "203"],
}
)
df1 = pd.DataFrame(
{
"patient address": df[["Addr1", "Addr2", "Addr3"]]
.fillna(" ")
.agg(" ".join, axis=1)
}
)
print(df1)
输出:
patient address
0 a 202
1 b x 201
2 c 203
添加回答
举报
0/150
提交
取消