Python 分组依据';日期';在计算其他列的平均值时
我有一个数据框,有3列:ID、日期、数据值报告温度记录(数据值),在给定的时间段内(日期-每天),来自不同的气象站(ID)。我需要的是每天“分组”,计算每天的平均温度,例如Python 分组依据';日期';在计算其他列的平均值时,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框,有3列:ID、日期、数据值报告温度记录(数据值),在给定的时间段内(日期-每天),来自不同的气象站(ID)。我需要的是每天“分组”,计算每天的平均温度,例如 ID | Date | Data_Value ------------------------------------ 12345 | 02-05-2017 | 22 12346 | 02-05-2017 | 24 12347 | 02-05-2017 | 20 123
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
有人能帮我解决这个问题吗?我想你需要并同意的意思是:
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
值:
或者如果只有ID
的第一个值通过以下方式聚合:
这很好用,没那么难…非常感谢!
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
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