[英]Creating an empty dataframe or List with column names then add data by column names
[英]List column names that are NULL/Empty for a Dataframe in each row
我有一個包含空/空值的數據框。
通過執行以下操作,我可以輕松獲取每行空值的計數:
df['NULL_COUNT'] = len(df[fields] - df.count(axis=1)
這將在字段NULL_COUNT
NULL
的列數。
如果列標題為空,有沒有辦法以相同的方式將列標題寫入另一個字段?
df['NULL_FIELD_NAMES'] = "<some query expression>"
例子:
df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)], columns=['A', 'B', 'C'])
在上面的 df 中,第二行應該有df['NULL_FIELD_NAME'] = 'B'
,第三行應該有df['NULL_FIELD_NAME'] = 'C'
您可以使用:
df['new'] = (df.isnull() * df.columns.to_series()).apply(','.join,axis=1).str.strip(',')
另一種解決方案:
df['new'] = df.apply(lambda x: ','.join(x[x.isnull()].index),axis=1)
樣本:
df = pd.DataFrame([range(3), [np.NaN, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)],
columns=['A', 'B', 'C'])
print (df)
A B C
0 0.0 1.0 2.0
1 NaN NaN 0.0
2 0.0 0.0 NaN
3 0.0 1.0 2.0
4 0.0 1.0 2.0
df['new'] = df.apply(lambda x: ','.join(x[x.isnull()].index),axis=1)
print (df)
A B C new
0 0.0 1.0 2.0
1 NaN NaN 0.0 A,B
2 0.0 0.0 NaN C
3 0.0 1.0 2.0
4 0.0 1.0 2.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.