假设我有一个包含列重复项的数据帧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]
我不知道怎么让熊猫去求它们的平均值。
发布于 2013-05-21 20:17:08
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
我认为需要注意的是避免列重复...或者我不知道我在做什么。
https://stackoverflow.com/questions/16678551
复制相似问题