示例資料:
dictionary = {'col1':[[1,2,3],[1,2,3],[1,2,3]],'col2': [[1,'nan',3],
[1,2,'nan'],[1,2,3]], 'col3': [[1,2,3],[1,2,3],[1,'nan',3]]}
df = pd.DataFrame(dictionary)
我有一個串列的 DataFrame,我想按行計算 NaN 值的數量:
col1 col2 col3
[1,2,3] [1,NaN,3] [1,2,3]
[1,2,3] [1,2,NaN] [1,2,3]
[1,2,3] [1,2,3] [1,NaN,3]
我用了
acceptable_data_df.iloc[:, 1:].apply(lambda x: list(itertools.chain(*x)), axis=1)
將它們轉換為一個串列,并希望使它更容易,但我仍然卡住了。(第一列是文本)
[1,2,3,1,NaN,3,1,2,3]
[1,2,3,1,2,NaN,1,2,3]
[1,2,3,1,2,3,1,NaN,3]
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您可以stack 獲得一個系列,其中explodeNaNisna為 True ,否則為 False 。然后groupby sum獲取每行 NaN 值的數量:
df['number of NaN'] = df.stack().explode().isna().groupby(level=0).sum()
輸出:
col1 col2 col3 number of NaN
0 [1, 2, 3] [1, nan, 3] [1, 2, 3] 1
1 [1, 2, 3] [1, 2, nan] [1, 2, 3] 1
2 [1, 2, 3] [1, 2, 3] [1, nan, 3] 1
uj5u.com熱心網友回復:
IIUC 用途:
df['count'] = (df.col1 df.col2 df.col3).apply(lambda x: pd.isna(x).sum())
uj5u.com熱心網友回復:
在將值保留為字串的同時計算“NaN”的一種“無聊”方法是僅計算"NaN"字串出現的次數:
(df["col1"] df["col2"] df["col3"]).str.count("NaN")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434033.html
