Python——如何按分钟对 Pandas DataFrame 进行分组?


我们将使用 groupby() 对 Pandas DataFrame 进行分组。使用 grouper 函数选择要使用的列。我们按分钟分组,并计算下面的汽车销售记录示例中 Registration Price 的和,其中分钟为间隔。

首先,假设下面是包含三列的 Pandas DataFrame。我们设置了 Date_of_Purchase,带有时间戳,同时包括日期和时间——

dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-07-28 00:10:00"),
         pd.Timestamp("2021-07-28 00:12:00"),
         pd.Timestamp("2021-07-28 00:15:00"),
         pd.Timestamp("2021-07-28 00:16:00"),
         pd.Timestamp("2021-07-28 00:17:00"),
         pd.Timestamp("2021-07-28 00:20:00"),
         pd.Timestamp("2021-07-28 00:35:00"),
         pd.Timestamp("2021-07-28 00:42:00"),
         pd.Timestamp("2021-07-28 00:57:00"),
      ],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

接下来,在 groupby 函数中使用 Grouper 选择 Date_of_Purchase 列。频率设置为 7min,即间隔 7 分钟分组——

print"\nGroup Dataframe by 7 minutes...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7min')).sum()

示例

以下是代码——

import pandas as pd

# dataframe with one of the columns as Date_of_Purchase
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-07-28 00:10:00"),
         pd.Timestamp("2021-07-28 00:12:00"),
         pd.Timestamp("2021-07-28 00:15:00"),
         pd.Timestamp("2021-07-28 00:16:00"),
         pd.Timestamp("2021-07-28 00:17:00"),
         pd.Timestamp("2021-07-28 00:20:00"),
         pd.Timestamp("2021-07-28 00:35:00"),
         pd.Timestamp("2021-07-28 00:42:00"),
         pd.Timestamp("2021-07-28 00:57:00"),
      ],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

print"DataFrame...\n",dataFrame

# Grouper to select Date_of_Purchase column within groupby function
print"\nGroup Dataframe by 7 minutes...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7min')).sum()

输出

这将生成以下输出——

DataFrame...
        Car    Date_of_Purchase   Reg_Price
0      Audi 2021-07-28 00:10:00        1000
1     Lexus 2021-07-28 00:12:00        1400
2     Tesla 2021-07-28 00:15:00        1100
3  Mercedes 2021-07-28 00:16:00         900
4       BMW 2021-07-28 00:17:00        1700
5    Toyota 2021-07-28 00:20:00        1800
6    Nissan 2021-07-28 00:35:00        1300
7   Bentley 2021-07-28 00:42:00        1150
8   Mustang 2021-07-28 00:57:00        1350

Group Dataframe by 7 minutes...
                    Reg_Price
Date_of_Purchase
2021-07-28 00:07:00    2400.0
2021-07-28 00:14:00    5500.0
2021-07-28 00:21:00       NaN
2021-07-28 00:28:00       NaN
2021-07-28 00:35:00    1300.0
2021-07-28 00:42:00    1150.0
2021-07-28 00:49:00       NaN
2021-07-28 00:56:00    1350.0

更新于: 2021-09-20

2K+ 浏览量

开启您的职业生涯

完成课程,获得认证

开始学习
广告