我有一个合并的数据框,如下所示:
>>> merged_df.dtypes
Jurisdiction object
AdjustedVolume float64
EffectiveStartDate datetime64[ns]
VintageYear int64
ProductType object
Rate float32
Obligation float32
Demand float64
Cost float64
dtype: object
以下 groupby 语句按管辖区/年份返回正确的调整卷值:
>>> merged_df.groupby(['Jurisdiction', 'VintageYear'])['AdjustedVolume'].sum()
当包含产品类型时:
>>> merged_df.groupby(['Jurisdiction', 'VintageYear','ProductType'])['AdjustedVolume'].sum()
如果管辖区仅包含一种产品类型,则按年份调整的销量是正确的,但对于具有两种或多种产品类型的任何管辖区,调整后的销量将被拆分,以便它们总和为正确的值。我期望每一行都有总的调整卷,但不清楚为什么要分割它。
示例:
>>> merged_df.groupby(['Jurisdiction', 'VintageYear'])['AdjustedVolume'].sum()
Jurisdiction VintageYear AdjustedVolume
CA 2017 3.529964e+05
>>> merged_df.groupby(['Jurisdiction', 'VintageYear','ProductType'])['AdjustedVolume'].sum()
Jurisdiction VintageYear ProductType AdjustedVolume
CA 2017 Bucket1 7.584832e+04
CA 2017 Bucket2 1.308454e+05
CA 2017 Bucket3 1.463026e+05
我怀疑 merge_asof 执行不正确:
>>> df1.dtypes
Jurisdiction object
ProductType object
VintageYear int64
EffectiveStartDate datetime64[ns]
Rate float32
Obligation float32
dtype: object
>>> df2.dtypes
Jurisdiction object
AdjustedVolume float64
EffectiveStartDate datetime64[ns]
VintageYear int64
dtype: object
由于 df2 没有 ProductType 字段,因此以下合并将总数量分解为每个管辖区下的任何 ProductType。我可以修改以下合并,以便每个 ProductType 都有总的 AdjustedVolume 吗?
merged_df = pd.merge_asof(df2, df1, on='EffectiveStartDate', by=['Jurisdiction','VintageYear'])
最佳答案
您可以使用两个版本的分组依据并合并两个表。 第一个表是一个包含 ProductType 的分组,它将按 ProductType 分割您的 AdjustedVolume。
df = df.groupby(['Jurisdiction','VintageYear','ProductType']).agg({'AdjustedVolume':'sum'}).reset_index(drop = False)
然后创建另一个表,不包含 ProductType(这是总金额的来源)。
df1 = df.groupby(['Jurisdiction','VintageYear']).agg({'AdjustedVolume':'sum'}).reset_index(drop = False)
现在在两个表中创建一个 ID 列,以便合并正常工作。
df['ID'] = df['Jurisdiction'].astype(str)+'_' +df['VintageYear'].astype(str)
df1['ID'] = df1['Jurisdiction'].astype(str)+'_'+ df1['VintageYear'].astype(str)
现在合并 ID 以获得调整后的总音量。
df = pd.merge(df, df1, left_on = ['ID'], right_on = ['ID'], how = 'inner')
最后一步是清理您的列。
df = df.rename(columns = {'AdjustedVolume_x':'AdjustedVolume',
'AdjustedVolume_y':'TotalAdjustedVolume',
'Jurisdiction_x':'Jurisdiction',
'VintageYear_x':'VintageYear'})
del df['Jurisdiction_y']
del df['VintageYear_y']
您的输出将如下所示:
关于python pandas merge_asof groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48447812/