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

如何对含1、0、-1的Paid列做透视表并统计总数与占比

生成包含总数与支付占比的透视表

假设你的数据集已加载为df,可按以下步骤实现目标格式的透视表:

  1. 生成基础状态统计透视表
    用pivot_table统计每日各支付状态的数量,同时填充缺失值为0避免日期出现空值:
import pandas as pd

# 生成基础透视表,统计各状态数量
pivot_df = pd.pivot_table(
    df,
    columns='Paid',
    index='date',
    aggfunc='count',
    values='Paid',
    fill_value=0
).rename(columns={1: '1', 0: '0', -1: '-1'})  # 对齐需求中的列名
  1. 计算每日总数
pivot_df['Total'] = pivot_df[['1', '0', '-1']].sum(axis=1)
  1. 计算支付状态占比
# 计算未支付占比(Paid0%)
pivot_df['Paid0%'] = (pivot_df['0'] / pivot_df['Total']).apply(lambda x: f"{x*100:.0f}%")
# 计算已支付占比(Paid1%)
pivot_df['Paid1%'] = (pivot_df['1'] / pivot_df['Total']).apply(lambda x: f"{x*100:.0f}%")
  1. 调整列顺序匹配需求
# 按目标格式重新排列列
final_df = pivot_df[['1', '0', '-1', 'Total', 'Paid0%', 'Paid1%']]

示例输出

执行后final_df会输出如下格式的结果:

date          1  0  -1   Total Paid0%  Paid1%
1st March    10  5   5   20     50%    50%
2nd March    5   4   1   10    40%      50%

内容的提问来源于stack exchange,提问作者Data Guy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:52:08