gpt4 book ai didi

python - 按 'Date' 分组,同时计算其他列的平均值

转载 作者:行者123 更新时间:2023-12-01 03:01:51 24 4
gpt4 key购买 nike

我有一个包含 3 列的数据框:ID、日期、Data_Value,报告给定时间段内(日期 - 每天)来自不同气象站 (ID) 的温度记录 (Data_Value)。我需要的是每天“分组”并计算每天的平均温度,例如

ID      |   Date       | Data_Value
------------------------------------
12345 | 02-05-2017 | 22
12346 | 02-05-2017 | 24
12347 | 02-05-2017 | 20
12348 | 01-05-2017 | 18
12349 | 01-05-2017 | 16

变成:

ID      |   Date       | Data_Value
------------------------------------
..... | 02-05-2017 | 22
..... | 01-05-2017 | 17

有人可以帮我解决这个问题吗?

最佳答案

我认为你需要groupby并聚合平均值:

df = df.groupby('Date', as_index=False, sort=False)['Data_Value'].mean()
print (df)
Date Data_Value
0 02-05-2017 22
1 01-05-2017 17

然后,如果还需要 ID 值,请使用 agg :

df = df.groupby('Date', as_index=False, sort=False)
.agg({'Data_Value':'mean', 'ID':lambda x: ','.join(x.astype(str))})
.reindex_axis(['ID','Date','Data_Value'], axis=1)
print (df)
ID Date Data_Value
0 12345,12346,12347 02-05-2017 22
1 12348,12349 01-05-2017 17

或者如果仅 ID 的第一个值按 first 聚合:

df = df.groupby('Date', as_index=False, sort=False) 
.agg({'Data_Value':'mean', 'ID':'first'})
.reindex_axis(['ID','Date','Data_Value'], axis=1)
print (df)

ID Date Data_Value
0 12345 02-05-2017 22
1 12348 01-05-2017 17

关于python - 按 'Date' 分组,同时计算其他列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43737952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com