簡體   English   中英

聚合pandas中的聚合值會返回錯誤的結果

[英]Aggregating on the aggregated values in pandas returns wrong result

我有這樣的數據框 - 每個事務可能出現多個,並且事務鏈接到商店。 我想找到交易的平均價值。 為此,我需要求和,然后找到平均值:

#preparind dataset
txt_data = pandas.read_csv("./TestDataSource/txn.csv", sep = ';')
txt_data = txt_data.replace({',': '.'}, regex=True)
txt_data[['SALES']] = txt_data[[ 'SALES']].apply(pd.to_numeric)

在此輸入圖像描述

我們len(txt_data.STORE.unique())這里只有30個獨特的STORE。

首先,我在交易上聚合:

a1 = txt_data[['STORE', 'SALES', 'TXN']].groupby('TXN').sum()[['STORE', 'SALES']]
a.head()

在此輸入圖像描述

一切似乎都沒問題。 但后來我在商店聚合:

a2 = a1.groupby('STORE').mean()
[![enter image description here][3]][3]

但是...... list(a2.shape) - 返回[ list(a2.shape) ]。 多數民眾贊成在困惑。 但是len(a1.STORE.unique())返回1137

我究竟做錯了什么

您有問題是按每個TXN列的sum匯總STORESALES列:

a1 = txt_data[['STORE', 'SALES', 'TXN']].groupby('TXN').sum()[['STORE', 'SALES']]

同樣如下:

a1 = txt_data.groupby('TXN')['STORE', 'SALES'].sum()

但如果按列TXTSTORE匯總,那么所有工作都很好:

txt_data = pd.read_csv("txn.csv", sep = ';', decimal=',')

a1 = txt_data.groupby(['TXN', 'STORE'], as_index=False)['SALES'].sum()

print (txt_data.STORE.nunique())
30

print (a1.STORE.nunique())
30

在線

a1 = txt_data[['STORE', 'SALES', 'TXN']].groupby('TXN').sum()[['STORE', 'SALES']]

您正在通過TXN對數據幀進行分組,但是告訴pandas將所有其他列相加,因此您可以將store-id求和並創建“新商店”,例如:

txt_data[txt_data['TXN']==5541359000]  

               DAY  STORE   ART                    TXN      TIME    SALES
1268877 2015-10-01  1082    15294488        5541359000  09:30:22    60.2
1269093 2015-10-01  1082    80439           5541359000  09:30:29    15.6
1269309 2015-10-01  1082    191452          5541359000  09:30:15    4.0
1269525 2015-10-01  1082    15317962        5541359000  09:30:17    103.0

a1.head()
           STORE    SALES
TXN     
5541359000  4328    182.8

#1082 * 4 = 4328

我認為當你使用這條線時你的問題就發生了,

a1 = txt_data[['STORE', 'SALES', 'TXN']].groupby('TXN').sum()

當我使用txt_data ['STORE']得到唯一值時,unique()輸出,

array([22691, 20581,  1574,  1602,  1579, 29245, 19009, 21761, 17474,
        1544,  1612,  1534,   958, 17096,  1094,  1596,  1594,  1609,
       24605,   956,   961,  1122, 27220,   974,  1082, 25039,  1530,
         999,  1053,   980])

但是在a1 Dataframe中,STORE值與txt_data不同,因為group_by.sum()在STORE中對值進行求和,以獲得唯一的'TXN'。 在此輸入圖像描述

請參閱:txt_data ['STORE']中沒有STORE = 4328。唯一()

在此輸入圖像描述

1082 * 4 = 4328

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM