我遇到了一个有关在 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
我本以为在重新取样时可以对布尔列进行简单的操作(比如求和),但是(实际上)这会失败:
>>> df.resample('5H').sum()
Nums
2020-01-01 05:00:00 10
2020-01-01 10:00:00 35
“Bools” 列已被删除。 我的印象是因为该列的 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
但是(奇怪的是)您仍然可以通过对重新采样对象进行索引来对布尔值求和,而不改变 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
函数不能执行该操作,如果可以做到的话。