Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 分组依据';日期';在计算其他列的平均值时_Python_Pandas_Dataframe - Fatal编程技术网

Python 分组依据';日期';在计算其他列的平均值时

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

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

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