簡體   English   中英

使用同一數據幀的特定列作為參考同時從多列填充 NaN 值的最佳方法

[英]Best way to fill NaN values from multiple columns at the same time using specific columns of the same dataframe as reference

例子:

DF = pd.DataFrame({'A': [0, 0, np.NaN, 0     , np.NaN, 0     , 0     , 0     ],
                   'B': [1, 1, np.NaN, 1     , np.NaN, 1     , 1     , 1     ],
                   'C': [8, 8, np.NaN, 8     , np.NaN, np.NaN, 8     , 8     ],
                   'D': [2, 2, 2     , np.NaN, np.NaN, 2     , np.NaN, np.NaN],
                   'E': [3, 3, 3     , np.NaN, np.NaN, 3     , np.NaN, np.NaN]})

我想要的預期結果是盡可能填充 A 列和 B 列,即:

   1) If DF['A'] line is NaN, it should get the correspondent DF['D'] line
   2) If DF['B'] line is NaN, it should get the correspondent DF['E'] line
   3) DF['C'] shall remain as it is

我想:

DF[['A', 'B']] = DF[['A','B']].fillna(DF[['D','E']])

但似乎只有當有兩個具有相同列名的不同數據框時它才會起作用。 我可以在 DF1 和 DF2 中拆分 DF,將 DF2['D'] 重命名為 A,將 DF2['E'] 重命名為 B 並執行以下操作:

DF1[['A', 'B']] = DF1[['A','B']].fillna(DF2[['A','B']])

但我認為這不是最好的方法。 有任何想法嗎?

實際數據集有 300 萬行,所以最好能得到最有效的解決方案 :)

謝謝!! :)

使用np.where是一個不錯的選擇,因為它適用於底層的 numpy 數組:

DF[['A','B']] = np.where(DF[['A','B']].isna(), DF[['D','E']], DF[['A','B']])

輸出:

     A    B    C    D    E
0  0.0  1.0  8.0  2.0  3.0
1  0.0  1.0  8.0  2.0  3.0
2  2.0  3.0  NaN  2.0  3.0
3  0.0  1.0  8.0  NaN  NaN
4  NaN  NaN  NaN  NaN  NaN
5  0.0  1.0  NaN  2.0  3.0
6  0.0  1.0  8.0  NaN  NaN
7  0.0  1.0  8.0  NaN  NaN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM