首页 > 解决方案 > Pandas 基于其他列重新采样列

问题描述

我有一个类似的数据框:

x | y
1 | 1
3 | 1
3 | 1
4 | 1
5 | 2
5 | 2
9 | 2
8 | 2

我想重新采样这个数据帧,以便平均具有相同 y 值的 x 值。换句话说:

     x       |    y
(1+3+3+4)/4  |    1
(5+5+9+8)/4  |    2

我研究了pandas.DataFrame.resample函数,但不确定如何在没有时间戳的情况下执行此操作。

标签: pythonpandasdataframe

解决方案


以下内容可能会返回您要查找的内容:

import pandas
df = pandas.DataFrame({"x":[1,3,3,4,5,5,9,8],"y":[1,1,1,1,2,2,2,2]})
df.groupby(["y"]).mean().reset_index()

推荐阅读