我刚刚将pandas从0.17.1更新到0.18.1,并认为我在更改一些预先存在的代码时发现了下面概述的新重采样方法的问题.根据此文档,我的下面示例中的df3_resample和df4_resample应返回相同的数据帧,但df4_resample会引发异常.这让我绊倒了一段时间,所以我想我会分享.
Exception: Column(s) A already selected
Run Code Online (Sandbox Code Playgroud)
http://pandas.pydata.org/pandas-docs/version/0.18.0/whatsnew.html#whatsnew-0180-breaking-resample
df = pd.DataFrame(np.random.rand(10,4),
columns=list('ABCD'),
index=pd.date_range('2010-01-01 09:00:00', periods=10, freq='s'))
df['item'] = 'item_a' # add column for groupby
# THIS WORKS
df1_resample = df.groupby('item').resample('2s').agg({'A': np.mean, 'B': np.max}).reset_index()
print df1_resample
# THIS WORKS
df2_resample = df.resample('2s').agg({'A': {'A_mean': np.mean, 'A_max': np.max}}).reset_index()
print df2_resample
# THIS WORKS
df3_resample = df.groupby('item').apply(lambda x: x.resample('2s').agg({'A': {'A_mean': np.mean, 'A_max': np.max}})).reset_index()
print df3_resample
# THIS DOESN"T WORKS
df4_resample = df.groupby('item').resample('2s').agg({'A': {'A_mean': np.mean, 'A_max': np.max}})
print df4_resample
Run Code Online (Sandbox Code Playgroud)
输出:
item level_1 A B
0 …Run Code Online (Sandbox Code Playgroud) 我有一个大型时间序列数据框,其中包含单独列中的数字和布尔数据。我正在尝试将数据从 1 分钟间隔缩减为 15 分钟间隔。布尔列是系统状态,我正在努力研究如何对它们进行下采样并仍然保留任何故障。目前,我的重新采样使用last将忽略任何行上发生的任何系统故障,但最后一行。
我希望它做什么:如果在 15 分钟系列中的任何行上发生“故障”,那么重采样后的时间戳将显示为“故障”,否则将显示为“正常”。
我知道解决方案存在于how=''resample 中,但是因为我是 numpy 和 pandas 的新手,所以我不知道要使用什么。
我的代码:
import pandas as pd
# Reads .csv, combines Date and Time columns into Timestamp, sets Timestamp as index
df = pd.read_csv('data.csv', parse_dates = {'Timestamp' : ['Date', 'Time']}, index_col = 'Timestamp')
# Fixing any incomplete data and interpolating any numerical gaps
index = pd.date_range(freq='1min', start=df.first_valid_index(), end=df.last_valid_index())
df_clean = df.reindex(set(df.index).union(index))
for col in df_clean:
df_clean[col] = df_clean[col].interpolate('time').ix[index]
# Downsampling numerical data
df_avg = …Run Code Online (Sandbox Code Playgroud)