gpt4 book ai didi

pandas - pandas Dataframe 中每月每列的缺失率

转载 作者:行者123 更新时间:2023-12-02 18:00:49 32 4
gpt4 key购买 nike

让我们采用以下pd.DataFrame

>>> df = pd.DataFrame({
'M' : ['1', '1' , '3', '6', '6', '6'],
'col1': [None, 0.1, None, 0.2, 0.3, 0.4],
'col2': [0.01, 0.1, 1.3, None, None, 0.5]})

创建

    M   col1  col2
0 1 NaN 0.01
1 1 0.1 0.10
2 3 NaN 1.30
3 6 0.2 NaN
4 6 0.3 NaN
5 6 0.4 0.50

我现在想要每列每月的缺失率百分比。结果表应该如下所示

M   col1  col2
1 50.0 0.0
3 100.0 0.0
6 0.0 66.6

其中 col1col2 单元格中的值表示该列每月的缺失率。

我该怎么做?

最佳答案

您可以使用 groupby.mean在 bool 列上:

out = (df.drop(columns='M').isna()  # check if the value is missing
.groupby(df['M']) # for each M
.mean().mul(100).round(2) # get the proportion x 100
.reset_index() # index as column
)

输出:

   M   col1   col2
0 1 50.0 0.00
1 3 100.0 0.00
2 6 0.0 66.67

关于pandas - pandas Dataframe 中每月每列的缺失率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74489906/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com