[英]Resampling boolean values in pandas
我遇到了一個屬性,我發現在pandas
中重新采樣布爾值很奇怪。 以下是一些時間序列數據:
import pandas as pd
import numpy as np
dr = pd.date_range('01-01-2020 5:00', periods=10, freq='H')
df = pd.DataFrame({'Bools':[True,True,False,False,False,True,True,np.nan,np.nan,False],
"Nums":range(10)},
index=dr)
所以數據看起來像:
Bools Nums
2020-01-01 05:00:00 True 0
2020-01-01 06:00:00 True 1
2020-01-01 07:00:00 False 2
2020-01-01 08:00:00 False 3
2020-01-01 09:00:00 False 4
2020-01-01 10:00:00 True 5
2020-01-01 11:00:00 True 6
2020-01-01 12:00:00 NaN 7
2020-01-01 13:00:00 NaN 8
2020-01-01 14:00:00 False 9
我原以為我可以在重采樣時對 boolean 列執行簡單的操作(如求和),但是(原樣)這失敗了:
>>> df.resample('5H').sum()
Nums
2020-01-01 05:00:00 10
2020-01-01 10:00:00 35
“布爾”列被刪除。 我對為什么會發生這種情況的印象是 b/c 列的dtype
是object
。 更改以解決問題:
>>> r = df.resample('5H')
>>> copy = df.copy() #just doing this to preserve df for the example
>>> copy['Bools'] = copy['Bools'].astype(float)
>>> copy.resample('5H').sum()
Bools Nums
2020-01-01 05:00:00 2.0 10
2020-01-01 10:00:00 2.0 35
但是(奇怪的是)您仍然可以通過索引重采樣 object 而不更改dtype
來對布爾值求和:
>>> r = df.resample('5H')
>>> r['Bools'].sum()
2020-01-01 05:00:00 2
2020-01-01 10:00:00 2
Freq: 5H, Name: Bools, dtype: int64
而且,如果唯一的列是布爾值,您仍然可以重新采樣(盡管該列仍然是object
):
>>> df.drop(['Nums'],axis=1).resample('5H').sum()
Bools
2020-01-01 05:00:00 2
2020-01-01 10:00:00 2
是什么讓后兩個示例起作用? 我可以看到它們可能更明確一點( “拜托,我真的想重新采樣此列!” ),但我不明白為什么如果可以完成原始resample
不允許該操作。
好吧,追蹤表明:
df.resample('5H')['Bools'].sum == Groupby.sum (in pd.core.groupby.generic.SeriesGroupBy)
df.resample('5H').sum == sum (in pandas.core.resample.DatetimeIndexResampler)
並且在groupby.py中跟蹤groupby_function
表明它相當於r.agg(lambda x: np.sum(x, axis=r.axis))
其中r = df.resample('5H')
輸出:
Bools Nums Nums2
2020-01-01 05:00:00 2 10 10
2020-01-01 10:00:00 2 35 35
好吧,實際上,它應該是r = df.resample('5H')['Bool']
(僅適用於上述情況)
並在resample.py中跟蹤_downsample
function 表明它相當於: df.groupby(r.grouper, axis=r.axis).agg(np.sum)
輸出:
Nums Nums2
2020-01-01 05:00:00 10 10
2020-01-01 10:00:00 35 35
df.resample('5H').sum()
不適用於Bools
列,因為該列具有混合數據類型,即object
中的 object。 在resample
或groupby
上調用sum()
時,將忽略object
類型的列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.