我有一个包含空/空值的dataframe。
通过执行以下操作,我可以轻松地获得空值的每一行的计数:
df['NULL_COUNT'] = len(df[fields] - df.count(axis=1)它将在字段NULL中放置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'。
发布于 2017-03-20 13:10:01
您可以使用:
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 https://stackoverflow.com/questions/42904255
复制相似问题