Python 计算非空值';表中若干列的百分比
对于如下所示的数据帧,如何计算熊猫中列Python 计算非空值';表中若干列的百分比,python,pandas,dataframe,Python,Pandas,Dataframe,对于如下所示的数据帧,如何计算熊猫中列a、C、D的非空值百分比?多谢各位 id A B C D 0 1 1.0 one 4.0 NaN 1 2 NaN one 14.0 NaN 2 3 2.0 two 3.0 -12.0 3 4 55.0 three NaN 12.0 4 5 6.0 two 8.0 12.0 5 6 NaN two 7.0 -1
a、C、D
的非空值百分比?多谢各位
id A B C D
0 1 1.0 one 4.0 NaN
1 2 NaN one 14.0 NaN
2 3 2.0 two 3.0 -12.0
3 4 55.0 three NaN 12.0
4 5 6.0 two 8.0 12.0
5 6 NaN two 7.0 -12.0
6 7 -17.0 one NaN NaN
7 8 NaN three 11.0 NaN
预期结果如下:
id A B C D
0 not-nulls_pct 62.5% NaN 75.0% 50.0%
1 1 1 one 4 NaN
2 2 NaN one 14 NaN
3 3 2 two 3 -12
4 4 55 three NaN 12
5 5 6 two 8 12
6 6 NaN two 7 -12
7 7 -17 one NaN NaN
8 8 NaN three 11 NaN
对于非NAN值的计数,请与一起使用
然后需要用缺少的值替换100%
,一个可能的解决方案,默认情况下使用-returnNaN
s,然后使用创建一行DataFrame
,并根据自定义值转置和前置,最后设置id
的第一个值:
s = df.notna().mean()
df1 = s.mul(100).astype(str).add('%').mask(s == 1).to_frame().T
df = pd.concat([df1, df], ignore_index=True)
df.loc[0, 'id'] = 'not-nulls_pct'
print (df)
id A B C D
0 not-nulls_pct 62.5% NaN 75.0% 50.0%
1 1 1 one 4 NaN
2 2 NaN one 14 NaN
3 3 2 two 3 -12
4 4 55 three NaN 12
5 5 6 two 8 12
6 6 NaN two 7 -12
7 7 -17 one NaN NaN
8 8 NaN three 11 NaN
或与loc
一起使用,则是最终数据帧中第一行的必要排序索引:
s = df.notna().mean()
df.loc[-1] = np.where(s != 1, s.mul(100).astype(str).add('%'), np.nan)
df = df.sort_index().reset_index(drop=True)
df.loc[0, 'id'] = 'not-nulls_pct'
print (df)
id A B C D
0 not-nulls_pct 62.5% NaN 75.0% 50.0%
1 1 1 one 4 NaN
2 2 NaN one 14 NaN
3 3 2 two 3 -12
4 4 55 three NaN 12
5 5 6 two 8 12
6 6 NaN two 7 -12
7 7 -17 one NaN NaN
8 8 NaN three 11 NaN
输出
id A B C D
0 1 1 one 4 NaN
1 2 NaN one 14 NaN
2 3 2 two 3 -12
3 4 55 three NaN 12
4 5 6 two 8 12
5 6 NaN two 7 -12
6 7 -17 one NaN NaN
7 8 NaN three 11 NaN
per 100.0% 62.5% 100.0% 75.0% 50.0%
非常感谢。你能补充一些解释吗?为什么需要mean()
?因为mean definions是数值的计数除以总计数。它工作得很好,因为Trues的处理方式类似于1
。我想计算所选列A、C、D
,但这并不重要。一切都好。:)
id A B C D
0 1 1 one 4 NaN
1 2 NaN one 14 NaN
2 3 2 two 3 -12
3 4 55 three NaN 12
4 5 6 two 8 12
5 6 NaN two 7 -12
6 7 -17 one NaN NaN
7 8 NaN three 11 NaN
per 100.0% 62.5% 100.0% 75.0% 50.0%