计算熊猫中几列的非空值百分比

时间:2019-09-19 08:53:44

标签: python pandas dataframe

对于以下数据框,如何计算熊猫中列not-null values的{​​{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

2 个答案:

答案 0 :(得分:2)

要计算非NaN值的数量,请使用DataFrame.notnaDataFrame.mean

然后有必要用丢失的值替换100%,用Series.mask替换一个可能的解决方案-默认返回NaN,然后用{{3}创建一行DataFrame },并在Series.to_frame之前进行转置和前缀,最后通过自定义值设置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

或将concatloc一起使用,则必须对最后DataFrame中的第一行进行排序索引:

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

答案 1 :(得分:1)

df.loc['per'] = ((df.count()/df.shape[0])*100).round(2).astype(str).add('%')

输出

    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%