1 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個贊
只需運(yùn)行 if 語句來檢查您是否有空值。
你可以使用fillna,但你會在兩邊都有不匹配的'__'。
conditions = [(df['numeric'].isnull()),
(df['object'].isnull())]
outputs = [df["object"].astype(str) + "__", df["numeric"].astype(str) + "__"]
df['both'] = np.select(conditions,outputs,default=
df['object'] + '__' + df['numeric'].astype(str))
print(df)
object numeric both
0 a 1.0 a__1.0
1 b 2.0 b__2.0
2 c NaN c__
3 NaN 4.0 4.0__
如果您正在使用,pandas 0.24+那么您可以利用Int64處理 nan 值的 dtype :
在這里閱讀更多
df['numeric'] = df['numeric'].astype('Int64')
df['both'] = np.select(conditions,outputs,default=
df['object'] + '__' + df['numeric'].astype(str))
print(df)
object numeric both
0 a 1 a__1
1 b 2 b__2
2 c NaN c__
3 NaN 4 4__
添加回答
舉報