7

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

パンダでこれを行うにはどうすればよいですか?

これまでのところ、重複を特定できました:

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

Pandasにそれらを平均化するように依頼する方法がわかりません。

4

1 に答える 1

5

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

奪うべきことは、列の重複を避けることだと思います...または、自分が何をしているのかわからないかもしれません。

于 2013-05-21T20:17:08.020 に答える