我有一个合并的数据帧,如下所示:
>>> 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语句按辖区/年份返回正确的调整后的体积值:
^{pr2}$包括产品类型时:
>>> merged_df.groupby(['Jurisdiction', 'VintageYear','ProductType'])['AdjustedVolume'].sum()
如果辖区仅包含一个ProductType,则按年调整的卷是正确的,但对于具有两个或多个ProductType的任何辖区,调整的卷将被拆分,以使它们总和为正确的值。我希望每一行都有调整后的总量,但不清楚为什么要分开。在
示例:
>>> 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
我怀疑合并错误:
>>> 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。我可以修改下面的合并,使每个产品类型都有调整后的总体积吗?在
merged_df = pd.merge_asof(df2, df1, on='EffectiveStartDate', by=['Jurisdiction','VintageYear'])
还可以考虑使用transform检索与其他记录内联的分组聚合,类似于SQL中的子查询聚合。在
您可以使用groupby的两个版本并合并两个表。 第一个表是一个带有ProductType的groupby,它将按ProductType分解调整后的卷。在
然后创建另一个表,不包含ProductType(这是总金额的来源)。在
^{pr2}$现在在两个表中创建一个ID列,以便合并能够正常工作。在
现在在IDs上合并得到调整后的总体积。在
最后一步是清理列。在
您的输出将如下所示:
相关问题 更多 >
编程相关推荐