pandas - dask - CSV 时间序列操作
问题描述
我有一个大小约为 5GB 的 CSV,数据结构和类型如下:
datetime product name serial number
0 2017-06-24 14:30:15 orange 123456
1 2017-07-04 21:33:50 apple 123456
2 2017-07-06 06:38:52 orange 123456
3 2017-07-10 15:52:07 banana 123456
4 2017-07-10 15:52:51 banana 123456
5 2017-07-10 15:53:18 banana 123456
6 2017-07-11 11:50:40 pineapple 123456
7 2017-07-11 00:53:43 apple 54321
8 2017-07-11 06:23:52 apple 54321
9 2017-07-11 06:23:52 apple 12454
10 2017-07-11 06:23:52 apple 12454
11 2017-07-11 06:23:52 apple 12454
12 2017-07-11 06:23:52 apple 15039
13 2017-07-11 06:23:52 apple 15037
14 2017-07-11 06:23:52 apple 15039
15 2017-07-11 06:23:52 apple 15190
16 2017-07-11 06:23:52 apple 15039
17 2017-07-11 06:23:52 apple 15037
18 2017-07-11 06:23:52 apple 15037
19 2017-07-11 06:23:52 apple 15037
....
few millions more lines
df.dtypes
Out[134]:
datetime datetime64[ns]
name object
events int64
dtype: object
问题 1:如何按产品名称分组,然后只统计前 10 个产品的序列号出现次数(出现次数最多的产品在顶部)?
# this does the count, but there are over 10,000 rows, and it is not sorted by counts f
df.groupby(['product name', 'serial number']).agg({'serial number':'count'}).compute()
# expected output (in table form):
product name serial number counts
orange 123456 2
orange 54321 12
apple 123456 1
apple 54321 4
pineapple 123456 16
问题 2:如何绘制一个产品名称的每个序列号在时间域内的出现情况?
问题 3:我真的很想绘制一个产品名称在时间域内出现的每个“序列号”,到目前为止,我可以使用以下方法从数据框中挑选出“产品名称”:
df_orange = df[df['proudct name'] == 'orange']
# how do I plot it?
解决方案
尽管我的两分钱是使用.cut
or来分箱.resample
,但我将展示一个简单的解决方案,您可以为每个解决方案运行product name
.
import pandas as pd
import matplotlib.pyplot as plt
# groupby twice
apple = (df.groupby('product name') # groupby 'product name'
.get_group('apple') # get 'apple' group
.groupby('datetime')) # groupby 'datetime'
apple1 = (apple['serial number'] # select 'serial number'
.agg(['value_counts'] # count the 'serial number's
.unstack(1) # this makes 'serial number's go across columns
.droplevel(axis=1, level=0)) # drop extra multiindex level name('value_counts')
apple1.plot(kind='bar') # plot it
plt.xticks(rotation=0) # because your 'datetime' is long and un-formatted
plt.yticks([i for i in range(5)]) # set xticks to int
plt.show()
对每个重复此操作,将product name
它们绘制为subplots
a Figure
,您将被设置
推荐阅读
- excel - 仅使用公式拆分分隔列
- prooph - 如何避免使用 prooph 的事件溯源?
- android - 如何避免由于自定义静态处理程序类导致的内存泄漏?
- c++ - SDL_RenderCopy 未渲染(不是 NULL,也没有 SDL/IMG 错误)
- ddev - ddev 开始卡在 Pulling web (drud/ddev-webserver:v1.4.0)
- c++ - 用于替换 GUI 生成器的运行时类型选择的 C++ 模式
- php - Laravel 将空值插入表单并将空值插入数据库
- javascript - 打字稿 - 复制功能不适用于返回值
- babeljs - 错误:使用带有 babel 7 的 nodemon 时监听 EADDRINUSE
- r - 在 SharePoint 中存储 R 项目