admin管理员组文章数量:1399906
I have the following data frame: enter image description here enter image description here
***>> df = pd.DataFrame(
{
"Tool": [1 , 2 , 1 , 2, 2, 2, 1, 2, 1,2],
"Timestamp": ['2022-05-28 05:03:00','2022-05-29 06:07:00','2022-05-28 07:11:00','2022-05-27 11:04:00','2022-05-27 05:43:00','2022-05-25 06:07:00','2022-05-28 11:22:00','2022-05-28 02:00:00','2022-05-26 04:22:00','2022-05-28 09:55:00'],
"Sensor1": [10,11,12,13,6,7,3,11,8,9],
"Sensor2": [5,4,3,3,5,4,3,3,8,2],
"Sensor3": [1,2,3,6,1,2,3,6,4,5],
}
)
>>df.groupby(['Tool', 'Timestamp'])[['Sensor1', 'Sensor2', 'Sensor3']].mean()***
But I'd like to group by the tool first and secondly group the sensor values by the same day (sensor value is mean value). Thanks
chatGPT provided suitable solution but I don't understand where appear parameter saying to group by day:
import pandas as pd
# Your DataFrame
df = pd.DataFrame(
{
"Tool": [1 , 2 , 1 , 2, 2, 2, 1, 2, 1,2],
"TimeStamp": ['2022-05-28 05:03:00','2022-05-29 06:07:00','2022-05-28 07:11:00','2022-05-27 11:04:00',
'2022-05-27 05:43:00','2022-05-25 06:07:00','2022-05-28 11:22:00','2022-05-28 02:00:00',
'2022-05-26 04:22:00','2022-05-28 09:55:00'],
"Sensor1": [10,11,12,13,6,7,3,11,8,9],
"Sensor2": [5,4,3,3,5,4,3,3,8,2],
"Sensor3": [1,2,3,6,1,2,3,6,4,5],
}
)
# Convert TimeStamp to datetime
df['TimeStamp'] = pd.to_datetime(df['TimeStamp'])
# Extract the date part of the timestamp
df['Date'] = df['TimeStamp'].dt.date
# Group by 'Tool' and 'Date', and calculate the mean of Sensor1, Sensor2, and Sensor3
result = df.groupby(['Tool', 'Date']).agg({
'Sensor1': 'mean',
'Sensor2': 'mean',
'Sensor3': 'mean'
}).reset_index()
print(result)
版权声明:本文标题:python - Pandas groupBy multiple columns and aggregation (group by frequency and then by value) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744224381a2596017.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论