繁体   English   中英

有没有办法计算交叉表 dataframe 与 pandas 中的另一个 dataframe 之间的比率?

[英]Is there a way to calculate ratio between a crosstab dataframe with another dataframe in pandas?

Summary - the end goal is to calculate the percentage based on the output from a crosstab function in Pandas with another dataframe at a shared index.

我尝试过的 - 尝试将原始交叉表 dataframe 拆分为分子并将另一个div拆分,但它似乎不起作用,因为结果都是nan

代码

import pandas as pd
import numpy as np 

df1 = pd.DataFrame({"Vntg": ["2020-01","2020-02","2020-03"],"Funded":[1000,2000,4000]}) # This is the df we want to use as denominator
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) # This is the crosstab df we want to use as numerator on a cumulative basis

cumsum开始累积付款,有没有办法通过df1中的资金金额转换/替换美元价值作为百分比? 在此先感谢并感谢所有帮助。

我还查看了下面的线程,它似乎没有解决我的问题: pd.crosstab() 的自定义规范化

编辑:

所以我认为有些人对这个问题感到困惑。 澄清一下,最终结果将是在时间 0 时从df2中取 10,然后除以资助金额,即 2020-01 年份的df1中的 1000。 对于 1 的后续时间,它只是来自df2的 (10+30) 并将相同的资助金额从df1用于相同的年份,因为它本质上没有改变。 结果将由其他年份的相同逻辑填充。

如果我理解这个问题,您想在相同的 Vntg 值内总结付款值,然后除以另一个 dataframe 的 Funded 字段和匹配的 Vntg 字段。

您可以通过对 Vntg 进行分组、求和并除以另一个 dataframe 来做到这一点:

df2.groupby('Vntg')['Payment'].sum() / df1.set_index('Vntg')['Funded'] * 100

下面的方法不使用crosstab ,但应该给出相同的答案(IIUC):

(
    df2.sort_values(["Vntg", "Timing"])
    .assign(cum_paymt=lambda df: df.groupby("Timing")["Payment"].transform("cumsum"))
    .assign(cum_share=lambda df: df["cum_paymt"] / df["Funded"])
    .pivot(index="Vntg", columns="Timing", values="cum_share")
)

如果把预期的 output 以 dataframe 的形式给出,对大家来说会更容易:

>>> ct_df.cumsum(axis=1).div(df1.set_index('Vntg')['Funded'], axis=0).mul(100)
Timing      0     1    2
Vntg                    
2020-01  1.00  3.00  5.0
2020-02  1.50  2.25  NaN
2020-03  0.75   NaN  NaN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM