gpt4 book ai didi

python - 数据透视表中的重复值

转载 作者:行者123 更新时间:2023-12-04 02:34:15 25 4
gpt4 key购买 nike

我有两个数据帧 df1df2。一个是客户债务,另一个是客户付款日期

我想创建一个新的数据框,其中包含在付款月份支付的债务百分比,直到 01-2017

问题是一些客户在同一个月内支付了两次费用,因此存在重复值,并且数据透视表无法以这种方式运行,它显示:ValueError:索引包含重复条目,无法 reshape

我该如何解决这个问题?

感谢您的宝贵时间!

import pandas as pd 

d1 = {'client number': ['2', '2','3','6','7','7','8','8','8','8','8','8','8','8'],
'month': [1, 2, 3,1,10,12,3,5,8,1,1,4,5,8],
'year':[2013,2013,2013,2019,2013,2013,2013,2013,2013,2014,2014,2015,2016,2017],
'payment' :[100,100,200,10000,200,100,300,500,200,100,200,200,500,50]}

df1 = pd.DataFrame(data=d1).set_index('client number')

d2 = {'client number': ['2','3','6','7','8'],
'debt': [200, 600,10000,300,3000]}

df2 = pd.DataFrame(data=d2)


df2 = df2.set_index('client number')

df1['pct'] = df1['payment'].div(df1.index.map(df2['debt'])).round(2)
df1['date'] = df1['year'].astype(str) + '-' + df1['month'].astype(str).str.zfill(2)
df3 = df2.join(df1.pivot(columns='date', values='pct').fillna(0)).reset_index()

最佳答案

使用,DataFrame.pivot_table使用 agg_func='sum',因为每月支付的债务的分数可以加在一起:

df3 = (
df2.join(
df1.pivot_table(index=df1.index, columns='date', values='pct', aggfunc='sum').fillna(0))
.reset_index()
)

结果:

# print(df3)

client number debt 2013-01 2013-02 2013-03 2013-05 2013-08 2013-10 2013-12 2014-01 2015-04 2016-05 2017-08 2019-01
0 2 200 0.5 0.5 0.00 0.00 0.00 0.00 0.00 0.0 0.00 0.00 0.00 0.0
1 3 600 0.0 0.0 0.33 0.00 0.00 0.00 0.00 0.0 0.00 0.00 0.00 0.0
2 6 10000 0.0 0.0 0.00 0.00 0.00 0.00 0.00 0.0 0.00 0.00 0.00 1.0
3 7 300 0.0 0.0 0.00 0.00 0.00 0.67 0.33 0.0 0.00 0.00 0.00 0.0
4 8 3000 0.0 0.0 0.10 0.17 0.07 0.00 0.00 0.1 0.07 0.17 0.02 0.0

关于python - 数据透视表中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62597289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com