在 pandas 中使用 group_by 但有条件

问题描述 投票:0回答:1

我有数据框

data = {'time': ['10:00', '10:01', '10:02', '10:02', '10:03','10:04', '10:06', '10:10', '10:15'],
        'price': [100, 101, 101, 103, 101,101, 105, 106, 107],
        'volume': [50, 60, 30, 80, 20,50, 10, 40, 40]}

我需要按此 df 每 5 分钟和价格进行分组,总结交易量

df.groupby([df['time'].dt.floor('5T'), 'price']).agg({'volume' : 'sum'}).reset_index()

然后我需要找到时间,当 pandas 将它们分组时,在求和新卷后我将获得超过 100 的值。

在这个 df 中,我找到 10:03,求和后,值将是 60 + 30 + 20 = 110。在 10:04 中,总和将是 60 + 30 + 20 + 50 = 160

我如何使用 pandas 来做到这一点?

python pandas group-by
1个回答
0
投票

您可以利用 pandas 中的

groupby()
函数,如下面的代码片段所示。

import pandas as pd

data = {
  'time': ['10:00', '10:01', '10:02', '10:02', '10:03','10:04', '10:06', '10:10', '10:15'],
  'price': [100, 101, 101, 103, 101,101, 105, 106, 107],
  'volume': [50, 60, 30, 80, 20,50, 10, 40, 40]
}

df = pd.DataFrame(data)

# Let's convert the time column to date and time
df['time'] = pd.to_datetime(df['time'])

# Then, use the groupby() function to group every 5 minutes and price, and sum up volume
grouped_df = df.groupby([pd.Grouper(key='time', freq='5Min'), 'price']).agg({'volume': 'sum'}).reset_index()

# We can now filter the dataframe as desired
filtered_df = grouped_df[grouped_df['volume'] > 100]

time_values = filtered_df['time']

print(time_values)
© www.soinside.com 2019 - 2024. All rights reserved.