pandas 在可空列上聚合

pandas支持group_by进行聚合,有如下Excel
在这里插入图片描述
按照A B C D四列进行聚合,其中D列可空也就是nan

import pandas as pd
from pandas import ExcelFile
from pathlib import Path
import os
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
sys.stdin = io.TextIOWrapper(sys.stdin.buffer,encoding='utf-8')

root_path = Path(__file__).absolute().parent
excel_path = os.path.join(root_path,'test.xlsx')

excel_sheetnames = ExcelFile(excel_path).sheet_names

df = pd.read_excel(excel_path,sheet_name=excel_sheetnames[0])
df['year_month'] = df['E'].dt.year.astype(str)+'-'+df['E'].dt.month.astype(str)
# 这句话很关键,否则NAN聚合会出为题
df['D'] = df['D'].astype(str)
vv = df.groupby(['A','B','C','D'])

# print(vv.grouper)
# print(vv.count())
# print(vv.value_counts())

for group_key in vv.groups.keys():
    value = vv.get_group(group_key)
    print('-------------------个数------------------')
    print(len(value))
    print(group_key)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值