python - Pandas :创建新的数据框,平均来自另一个数据框的重复项

标签 python pandas

假设我有一个包含重复列的数据框 my_df,例如

foo bar foo hello
0   1   1   5
1   1   2   5
2   1   3   5

我想创建另一个平均重复数据的数据框:

foo bar hello
0.5   1   5
1.5   1   5
2.5   1   5

我如何在 Pandas 中执行此操作?

到目前为止,我已经设法识别出重复项:

my_columns = my_df.columns
my_duplicates = print [x for x, y in collections.Counter(my_columns).items() if y > 1]

我不知道如何让 Pandas 对它们进行平均。

最佳答案

您可以 groupby列索引并取 mean :

In [11]: df.groupby(level=0, axis=1).mean()
Out[11]:
   bar  foo  hello
0    1  0.5      5
1    1  1.5      5
2    1  2.5      5

一个有点棘手的例子是如果有一个非数字列:

In [21]: df
Out[21]:
   foo  bar  foo hello
0    0    1    1     a
1    1    1    2     a
2    2    1    3     a

以上将引发:DataError: No numeric types to aggregate绝对不会赢得任何奖励效率,但这里是在这种情况下的通用方法:

In [22]: dupes = df.columns.get_duplicates()

In [23]: dupes
Out[23]: ['foo']

In [24]: pd.DataFrame({d: df[d] for d in df.columns if d not in dupes})
Out[24]:
   bar hello
0    1     a
1    1     a
2    1     a

In [25]: pd.concat(df.xs(d, axis=1) for d in dupes).groupby(level=0, axis=1).mean()
Out[25]:
   foo
0  0.5
1  1.5
2  2.5

In [26]: pd.concat([Out[24], Out[25]], axis=1)
Out[26]:
   foo  bar hello
0  0.5    1     a
1  1.5    1     a
2  2.5    1     a

我认为要避免的是避免列重复...或者我不知道自己在做什么。

关于python - Pandas :创建新的数据框,平均来自另一个数据框的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678551/

相关文章:

python - 从具有复合(分层)索引的 Pandas 数据框中选择行

python - 带次要 y 轴的 Pandas 条形图 : hide grid line below plot

python - 如何获取我在 pymysql 中插入的行的 IDENTITY/AUTONUMBER 值

python - setuptools - 从相对路径从框架 bundle

Python:写入 xml 文件时丢失内容

python - 向量化前瞻性函数 pandas 数据框

python - 是否有一种有效的方法来过滤并将函数应用于该数据集?

python - Django Rest框架在extra_kwargs字典中传递字段错误

python - 可以在没有屏幕的情况下运行 Pymunk 模拟(就像没有实际看到它一样)?

python - 列索引器中的 bool 表达式 (Pandas) 'is' 运算符不起作用