在某些条件下使用计数方法对数据帧重新采样

Jer*_*oen 6 python-3.x pandas

我正在尝试从数据框中重新采样数据。列有不同类型的数据。对于其中一列,我想计算该列的值大于 0 的行数。

一个小例子如下所示:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'Date': pd.date_range('2018-01-01','2018-01-15'),
                        'A': np.random.randint(5, size=15)})
df.set_index(df.Date, inplace=True)

df.resample('5D').count()
Run Code Online (Sandbox Code Playgroud)

计数有效,但我找不到插入条件的方法,即我只想计算大于 0 的值。如下所示:

df.resample('5D').count(df[df.A > 0])
Run Code Online (Sandbox Code Playgroud)

然而,TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

问题:如何resample().count()有条件

jez*_*ael 6

您可以使用Resampler.applysumof Trues 值,这些值是像1s 这样的过程:

np.random.seed(57)

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'Date': pd.date_range('2018-01-01','2018-01-15'),
                        'A': np.random.randint(5, size=15)})
df.set_index(df.Date, inplace=True)

df1 = df.resample('5D')['A'].apply(lambda x: (x > 0).sum())
print (df1)
Date
2018-01-01    2
2018-01-06    3
2018-01-11    4
Name: A, dtype: int64
Run Code Online (Sandbox Code Playgroud)

或者更好的解决方案是创建布尔掩码并使用resample聚合sum

df1 = (df['A'] > 0).resample('5D').sum().astype(int)
print (df1)

Date
2018-01-01    2
2018-01-06    3
2018-01-11    4
Name: A, dtype: int32
Run Code Online (Sandbox Code Playgroud)