2017-03-23 84 views
1

我是一個新手,我試着看幾個帖子,似乎無法得到這個工作...我是問題,我敢肯定。熊貓TimeGrouper&合併datetimeindex

試圖合併和壓縮兩個數據集,一個具有購買水果的日期和重量,另一個具有歷史每日價格。我試圖將這些內容壓縮到每週一次。

的原始數據,我想從長相創建Weights這樣的:

Date  Product  Weight 
1-1-12  Strawberry  15 
1-2-12  Bananna  56 
1-2-12  Apple   98 
1-5-12  Strawberry 115 
1-5-12  Bananna  516 
1-5-12  Apple   981 

下面是我試圖創建一個數據幀的代碼,但返回一個系列:

df_GrossWeight = pd.read_csv('mydata.csv', encoding='utf-8') 
df_GrossWeight_Indexed = df_GrossWeight.set_index(pd.DatetimeIndex(df_GrossWeight['Date'])) 
grouper = df_GrossWeight_Indexed.groupby([pd.TimeGrouper('W'),'Product']) 
Weights = grouper['Weight'].sum() 

我希望將其與我創建的系列Prices合併,該系列列出每週價格:

(datetimeindex)  Product  Price 
2012-01-1   Strawberry 2.10 
2012-01-1   Banana  0.55 
2012-01-1   Apple   1.25 

下面的代碼來創建Prices,我用:

df_Price = pd.read_csv('Price_Hist.csv') 
df_Indexed = df_Price.set_index(pd.DatetimeIndex(df_Price['Date']), drop = True) 
df_Price_Indexed = df_Indexed['Price'] 
Prices = df_Price_Indexed.resample('W').mean() 

最終數據框,我試圖讓將有每週的價格和我們買了多少金額週刊。它看起來是這樣的:

(datetimeindex)  Product  Price  Weight 
    2012-01-1   Strawberry 2.10  130 
    2012-01-1   Banana  0.55  572 
    2012-01-1   Apple   1.25  1079 

我得到這個可以做的比我如何想簡單了很多的感覺,所以任何的幫助深表感謝。

謝謝你在前進, 我做這件事

回答

1

確保您Date欄是日期

Weights.Date = pd.to_datetime(Weights.Date) 

還要確保修復香蕉錯字。

我們可以使用pd.merge_asof來查找小於或等於目標日期的最近日期。

pd.merge_asof(
    Weights, Prices, left_on=['Date'], right_on=['(datetimeindex)'], by='Product' 
).groupby(
    ['(datetimeindex)', 'Product'] 
).agg(dict(Weight='sum', Price='mean')).reset_index() 

    (datetimeindex)  Product Price Weight 
0  2012-01-01  Apple 1.25 1079 
1  2012-01-01  Banana 0.55  572 
2  2012-01-01 Strawberry 2.10  130 
+0

如果投票人仍在看這篇文章,我想解決您的疑慮,並可能說服您刪除投票。如果可以的話,請讓我知道這篇文章有什麼問題。它沒有用嗎? – piRSquared

2

一種方式是「圓」的所有日期最近的工作日。一旦你有這個'四捨五入'的日期。您可以加入兩個數據框。

df['Date'] = pd.to_datetime(df['Date']) 
df2['(datetimeindex)'] = pd.to_datetime(df2['(datetimeindex)']) 

舍入到最近週日

df2['Week_Sunday'] = df2['(datetimeindex)'] + pd.tseries.offsets.Week(weekday=6) 
df['Week_Sunday'] = df.Date + pd.tseries.offsets.Week(weekday=6) 

現在合併數據

df_all = pd.merge(df2, df, on = ['Week_Sunday', 'Product']) 
print(df_all) 

輸出

(datetimeindex)  Product Price Week_Sunday  Date Weight 
0  2012-01-01 Strawberry 2.10 2012-01-08 2012-01-01  15 
1  2012-01-01 Strawberry 2.10 2012-01-08 2012-01-05  115 
2  2012-01-01  Banana 0.55 2012-01-08 2012-01-02  56 
3  2012-01-01  Banana 0.55 2012-01-08 2012-01-05  516 
4  2012-01-01  Apple 1.25 2012-01-08 2012-01-02  98 
5  2012-01-01  Apple 1.25 2012-01-08 2012-01-05  981 

GROUPBY和總結

df_all.groupby(['(datetimeindex)', 'Product', 'Price'], as_index=False)['Weight'].sum() 

(datetimeindex)  Product Price Weight 
0  2012-01-01  Apple 1.25 1079 
1  2012-01-01  Banana 0.55  572 
2  2012-01-01 Strawberry 2.10  130