目標
以 30 秒為間隔對 pandas 資料框進行分組并提取資料以繪制它。
例子
import pandas as pd
log = [
['2022/10/10_6:13:39', '6328f0c6ad70889fd28dcd07'],
['2022/10/10_6:13:49', '6328f0c6ad70889fd28dcd07'],
['2022/10/10_6:14:23', '6328f0c6ad70889fd28dcd07'],
['2022/10/10_6:14:25', '6328b959a5745f6fa5206fa6'],
['2022/10/10_6:15:4', '6328b959a5745f6fa5206fa6'],
['2022/10/10_6:15:52', '628fa4ac88be7ffeb9b7e7e3']]
df = pd.DataFrame(log,
columns=['timestamp', 'data'])
# convert to timestamp format
df['timestamp'] = pd.to_datetime(df['timestamp'],format='%Y/%m/%d_%H:%M:%S')
資料框:
timestamp data
0 2022-10-10 06:13:39 6328f0c6ad70889fd28dcd07
1 2022-10-10 06:13:49 6328f0c6ad70889fd28dcd07
2 2022-10-10 06:14:23 6328f0c6ad70889fd28dcd07
3 2022-10-10 06:14:25 6328b959a5745f6fa5206fa6
4 2022-10-10 06:15:04 6328b959a5745f6fa5206fa6
5 2022-10-10 06:15:52 628fa4ac88be7ffeb9b7e7e3
我的方法
# Group in intervals
g = df.groupby(pd.Grouper(key='timestamp',freq='30s'))
問題
- 我想查看分組資料框。我怎么做?
- 我想繪制每個間隔內有多少唯一資料。
uj5u.com熱心網友回復:
當您使用 group by 時,如果您想要可以使用的值的數量,您需要一個聚合函式count()。要檢查分組的資料,您可以使用串列。然后您可以使用條形圖繪制資料
grouped_data = df.groupby(pd.Grouper(key='timestamp',freq='30s')).agg(list)
grouped_counts = df.groupby(pd.Grouper(key='timestamp',freq='30s')).count()
grouped_counts.plot(kind='bar')

編輯唯一值
如果您想要唯一的值,您可以按集合聚合并計算值
grouped_data = df.groupby(pd.Grouper(key='timestamp',freq='30s')).agg(set)
grouped_data['counts'] = grouped_data['data'].apply(lambda x: len(x))
grouped_data.plot(y='counts', kind='bar')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515892.html
標籤:Python熊猫列表阴谋
