【发布时间】:2020-02-19 09:15:01
【问题描述】:
假设我正在测量汽车沿单轴前进的速度随时间变化,每 10 分钟测量一次。
我的 DataFrame 中有一个名为 delta_x 的列,其中包含过去 10 分钟内汽车在我的轴上移动了多少,值只是整数。
现在假设我想聚合我的数据,并且只有每小时的移动量,但我想尽可能优化我的代码,因为我的数据集非常大,最有效的实现方式是什么那个?
df.head(9)
date time delta_x
0 01/01/2018 00:00 9
1 01/01/2018 00:10 9
2 01/01/2018 00:20 9
3 01/01/2018 00:30 9
4 01/01/2018 00:40 11
5 01/01/2018 00:50 12
6 01/01/2018 01:00 10
7 01/01/2018 01:10 10
8 01/01/2018 01:20 10
目前我的解决方案是执行以下操作
for file in os.listdir('temp'):
if(file.endswith('.txt'):
df = pd.read_csv(''.join(["./temp/",file]), header=None, delim_whitespace=True)
df.columns = ['date', 'time', 'delta_x']
df['hour'] = [(datetime.strptime(x, "%H:%M")).hour for x in df['time'].values]
df = df.groupby(['date','hour']).agg({'delta_x': 'sum'})
哪个输出正确:
date hour delta_x
01/01/2018 0 59
但我想知道,有没有更好、更快、更有效的方法,也许是使用 NumPy ?
【问题讨论】:
标签: python-3.x pandas numpy dataframe pandas-groupby