You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按Country分组统计空值、有效行及标记缺失行需求

按Country分组处理DataFrame缺失值统计

原始DataFrame

import pandas as pd

df = pd.DataFrame({
    'Country': ['CZ', 'AE', 'AE', 'AE', 'CZ', 'DK', 'DK', 'PT', 'PT'],
    'Name': ['Paulo']*9,
    'Code': [3, 'Yes', 'Yes', 1, None, 'Yes', None, 2, 1],
    'Signed': ['x', None, None, 'Yes', None, None, None, 'Yes', 'Yes'],
    'Index': [1, 1, 2, 5, 6, 9, 20, 20, 22]
})

需求

  • 按Country分组后生成以下统计列:
    1. Total_Blanks_on_Code:Code列缺失值(None)的数量
    2. Total_Blanks_on_Signed:Signed列缺失值的数量
    3. Total_of_rows_with_both_values_filled:Code和Signed均无缺失的行数(无符合行则显示None)
    4. Total_of_rows_of_the_Country:该Country的总行数
    5. Rows with any blank:该Country下存在任一缺失值的行的Index值(单个值直接显示,多个值以列表展示)
  • 移除所有Code和Signed均无缺失的Country

实现代码

def group_stats(group):
    # 统计各列缺失数
    blank_code = group['Code'].isna().sum()
    blank_signed = group['Signed'].isna().sum()
    # 统计两列均填充的行数
    both_filled = ((~group['Code'].isna()) & (~group['Signed'].isna())).sum()
    # 总行数
    total_rows = len(group)
    # 提取有缺失的行的Index
    any_blank_indices = group.loc[group['Code'].isna() | group['Signed'].isna(), 'Index'].tolist()
    # 单个值时直接返回数值,避免列表格式
    if len(any_blank_indices) == 1:
        any_blank_indices = any_blank_indices[0]
    # 返回统计结果
    return pd.Series({
        'Total_Blanks_on_Code': blank_code,
        'Total_Blanks_on_Signed': blank_signed,
        'Total_of_rows_with_both_values_filled': both_filled if both_filled != 0 else None,
        'Total_of_rows_of_the_Country': total_rows,
        'Rows with any blank': any_blank_indices
    })

# 分组聚合并重置索引
result = df.groupby('Country').apply(group_stats).reset_index()

# 过滤掉无缺失值的Country
result = result[(result['Total_Blanks_on_Code'] > 0) | (result['Total_Blanks_on_Signed'] > 0)]

运行结果

Country  Total_Blanks_on_Code  Total_Blanks_on_Signed Total_of_rows_with_both_values_filled  Total_of_rows_of_the_Country  Rows with any blank
0      CZ                     1                       1                                  None                             2                    6
1      AE                     0                       2                                     1                             3                   [1,2]
2      DK                     1                       2                                  None                             2                   [9,20]

注:原始需求中AE的Total_Blanks_on_Code标注为2,但根据原始数据,AE的Code列无None值,实际缺失数为0。

内容的提问来源于stack exchange,提问作者Paulo Cortez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:15:40