簡體   English   中英

通過不同的頻率采樣熊貓數據幀

[英]sampling pandas dataframe by different frequencies

我有一個以ID和時間戳為鍵的多索引系列/數據框。 該數據結構具有各種ID的每日數據。 我可以使用重采樣功能查看此數據結構的月末快照嗎?

ID ts           value 
1  2001-01-30   1
   2001-01-31   2
   2001-02-01   3
2  2001-01-30   3
   2001-01-31   2
   2001-02-01   4

我想要這個輸出

ID  ts          value
1   2001-01-31  2
2   2001-01-31  2

我可以使用resample函數調用來幫助我嗎? 我知道我可以創建月末日期列表並遍歷這些日期並找到這些值。 但是我想使用熊貓的全部功能。

為什么需要重新采樣? 只需將索引設置為ts然后切片,就像這樣:

from cStringIO import StringIO
raw = """id  ts     value
1  2001-01-30   1
1  2001-01-31   2
1  2001-02-01   3
2  2001-01-30   3
2  2001-01-31   2
2  2001-02-01   4"""
sio = StringIO(raw)
df = read_csv(sio, sep=r'\s+', header=0, parse_dates=[1])
df.set_index('ts', inplace=True)

切片然后重置索引:

print df['2001-01-31'].reset_index().set_index('id')

導致:

                    ts  value
id                           
1  2001-01-31 00:00:00      2
2  2001-01-31 00:00:00      2

如果您不關心月末值是否不存在,那么可以執行以下操作:

df.groupby('id', as_index=False).resample('M', how='last')

這使

            id  value
ts                   
2001-01-31   1      2
2001-02-28   1      3
2001-01-31   2      2
2001-02-28   2      4

暫無
暫無

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

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