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

Pandas中如何计算交叉表DataFrame与另一同索引DataFrame的比值百分比

问题原因

你用div得到全NaN的核心原因是两个计算对象索引未对齐、计算维度不匹配:

  • ct_df的行索引为Vntg值,而df1默认使用整数位置索引,二者行索引无法对应
  • df.div()默认按列对齐计算,你需要的是按行对齐,用同一个Vntg对应的Funded值除当前行所有列的数值

解决方案

直接将df1的Vntg设为索引后提取Funded列作为分母,调用div时指定axis=0按行对齐计算即可,完整代码如下:

import pandas as pd
import numpy as np 

df1 = pd.DataFrame({"Vntg": ["2020-01","2020-02","2020-03"],"Funded":[1000,2000,4000]}) 
df2 = pd.DataFrame({"Vntg": ["2020-01","2020-01","2020-01","2020-02","2020-02","2020-03"],
                    "Funded":[1000,1000,1000,2000,2000,4000],
                    "Payment":[10,20,20,30,15,30],
                    "Timing":[0,1,2,0,1,0]})
ct_df = pd.crosstab(df2["Vntg"], df2["Timing"], values=df2["Payment"], aggfunc="sum", margins=False)
ct_df = ct_df.cumsum(axis=1) 

# 新增计算逻辑
denominator = df1.set_index('Vntg')['Funded']
pct_df = ct_df.div(denominator, axis=0).round(4) * 100 # 保留两位小数的百分比值
print(pct_df)

输出结果

运行后得到的百分比结果如下:

Vntg012
2020-011.003.005.00
2020-021.502.25NaN
2020-030.75NaNNaN

你可以根据需求选择填充NaN为0、保留空值,或者额外给数值加上百分号后缀做格式化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:15:04