我正在聚合我的 df:
dfAvg_Volume_RFQ = dfSpecific_Client_Avg_Volume_RFQ.groupby(['Client', 'currency', 'sales_person_name2']).agg({'state': 'size', 'Quantity': 'mean', 'Quantity_CAD': 'mean'})
print(dfAvg_Volume_RFQ.info())
MultiIndex: 1127 entries, (A......) to (Z.....)
Data columns (total 3 columns):
state 1127 non-null int64
Quantity 1127 non-null float64
Quantity_CAD 1127 non-null float64
当我查看 df 的头部时,它显示了所有六列。当我在 dfSpecific_Client_Avg_Volume_RFQ 上运行其他聚合时,它仅使用 info 中的三列,这是一个问题。
print(dfAvg_Volume_RFQ.head(5))
state Quantity \
Client currency sales_person_name2
A USD OSCAR 2 2050000.0000
AA USD NAZ 10 11500000.0000
AAR USD JOSHUA 1 15000.0000
ABC USD ANGELA 1 5000000.0000
HANS 1 10000000.0000
Quantity_CAD
Client currency sales_person_name2
A USD OSCAR 2 2050000.0000
AA USD NAZ 10 11500000.0000
AAR USD JOSHUA 1 15000.0000
ABC USD ANGELA 1 5000000.0000
HANS 1 10000000.0000
print(dfAvg_Volume_RFQ.columns)
state Quantity Quantity_CAD
0 1 50000000.0000 47523999.6198
1 4 300000000.0000 399625821.9816
2 18 274241666.6667 365848851.3870
3 1 300000000.0000 409165302.7823
4 32 138905156.2500 138905156.2500
print (dfAvg_Volume_RFQ.index.names)
Index(['state', 'Quantity', 'Quantity_CAD'], dtype='object')
['Client', 'currency', 'sales_person_name2']
当对大量列进行分组和求和时,是否不可能在没有多重索引的情况下生成 df?
最佳答案
我认为这是预期的,因为没有 6 列,而是 3 级 MultiIndex 和 3 列。
测试方法:
print (dfAvg_Volume_RFQ.columns)
print (dfAvg_Volume_RFQ.index.names)
如果需要将 MultiIndex
转换为列,请使用 DataFrame.reset_index
或groupby
中的参数as_index=False
:
dfAvg_Volume_RFQ = dfAvg_Volume_RFQ.reset_index()
或者:
dfAvg_Volume_RFQ = dfSpecific_Client_Avg_Volume_RFQ.groupby(['Client', 'currency', 'sales_person_name2'], as_index=False)
.agg({'state': 'size', 'Quantity': 'mean', 'Quantity_CAD': 'mean'}
关于python - 由于多重索引,Pandas 聚合 df 显示 head() 和 .info() 之间的列数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181516/