我想将许多包含 Nan 值的列连接/连接到一个新列。
如何避免/传递连接结果中的 NaN?
下面只是为了展示我的尝试,我同时使用了 .agg
和 .apply
。
import pandas as pd
import numpy as np
df = pd.DataFrame({'foo':['a',np.nan,'c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})
subcat_names=["foo","new"]
df["result"] = df[subcat_names].astype(str).agg(','.join, axis=1)
df=df.fillna("")
df["result_2"] =df[subcat_names].apply(lambda x : '{},{}'.format(x[0],x[1]), axis=1)
print(df)
foo bar new result result_2
0 a 1 apple a,apple a,apple
1 2 banana nan,banana ,banana
2 c 3 pear c,pear c,pear
结果 nan,
是不需要的
在 result_2 处,
是不需要的
谢谢
最佳答案
您可以尝试pd.notnull()
subcat_names = ["foo", "new"]
df["result"] = df[subcat_names].apply(lambda x: ",".join(x[pd.notnull(x)]), axis=1)
print(df)
输出:
foo bar new result
0 a 1 apple a,apple
1 2 banana banana
2 c 3 pear c,pear
关于python - 连接多列在数据框中包含 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75056442/