我有一個關于如何根據幾個列值創建新列的問題。
輸入:
col1 col2 col3
1 1 1
NULL NULL NULL
2 NULL 2
NULL NULL 3
4 NULL NULL
5 5 NULL
輸出
col1 col2 col3 new
1 1 1 1
NULL NULL NULL NULL
2 NULL 2 2
NULL NULL 3 3
4 NULL NULL 4
5 5 NULL 5
我正在嘗試使用 combine_first,但這似乎不是一個好的選擇,因為我有多個列需要組合。
uj5u.com熱心網友回復:
一種選擇是rename使列具有相同的名稱;然后使用groupby first:
df['new'] = (df.rename(columns={col: 'col' for col in df.columns})
.groupby(level=0, axis=1).first())
您也可以迭代地使用combine_first:
df['new'] = float('nan')
for c in df.columns:
df['new'] = df['new'].combine_first(df[c])
或者你可以應用一個 lambda 來逐行選擇非 NaN 值(適用于 Python>=3.8,因為它使用海象運算子;如果你有 Python<3.8,則可以以不同的方式撰寫相同的函式):
df['new'] = df.apply(lambda x: res[0] if (res:=x[x.notna()].tolist()) else float('nan'), axis=1)
輸出:
col1 col2 col3 new
0 1.0 1.0 1.0 1.0
1 NaN NaN NaN NaN
2 2.0 NaN 2.0 2.0
3 NaN NaN 3.0 3.0
4 4.0 NaN NaN 4.0
5 5.0 5.0 NaN 5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439389.html
