具体的な問題として、DataFrame DFがあるとします
word tag count
0 a S 30
1 the S 20
2 a T 60
3 an T 5
4 the T 10
見つけたい、それぞれの「単語」について、最も「カウント」が多い「タグ」. リターンは次のようになります
word tag count
1 the S 20
2 a T 60
3 an T 5
カウント列や順序/インデックスがオリジナルか間違っているかは気にしません。辞書を返す{'その' : 'S'、...} で十分です。
できればいいな
DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] )
しかし、動作しません。列情報にアクセスできません。
もっと抽象的に言えば、何ですか関数合計で(関数)その議論として見る?
ところで、 .agg() は .aggregate() と同じですか?
どうもありがとう。
ベストアンサー1
agg
は と同じですaggregate
。その呼び出し可能オブジェクトには、Series
の列 ( オブジェクト) がDataFrame
1 つずつ渡されます。
idxmax
最大カウントを持つ行のインデックス ラベルを収集するには、次のようにします。
idx = df.groupby('word')['count'].idxmax()
print(idx)
収穫
word
a 2
an 3
the 1
Name: count
次に、 を使用して、および列loc
内の行を選択します。word
tag
print(df.loc[idx, ['word', 'tag']])
収穫
word tag
2 a T
3 an T
1 the S
idxmax
インデックスを返すことに注意してくださいラベル. はdf.loc
ラベルで行を選択するために使用できます。ただし、インデックスが一意でない場合、つまり重複したインデックスラベルを持つ行がある場合、次のようにdf.loc
選択されます。すべての行にリストされているラベルを使用します。idx
したがって、df.index.is_unique
True
idxmax
df.loc
代わりに、 を使用することもできますapply
。apply
の呼び出し可能オブジェクトには、すべての列にアクセスできるサブ DataFrame が渡されます。
import pandas as pd
df = pd.DataFrame({'word':'a the a an the'.split(),
'tag': list('SSTTT'),
'count': [30, 20, 60, 5, 10]})
print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
収穫
word
a T
an T
the S
とを使用するidxmax
と、特に大規模な DataFrame の場合、loc
通常は よりも高速になります。IPython の %timeit を使用する場合:apply
N = 10000
df = pd.DataFrame({'word':'a the a an the'.split()*N,
'tag': list('SSTTT')*N,
'count': [30, 20, 60, 5, 10]*N})
def using_apply(df):
return (df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
def using_idxmax_loc(df):
idx = df.groupby('word')['count'].idxmax()
return df.loc[idx, ['word', 'tag']]
In [22]: %timeit using_apply(df)
100 loops, best of 3: 7.68 ms per loop
In [23]: %timeit using_idxmax_loc(df)
100 loops, best of 3: 5.43 ms per loop
単語をタグにマッピングする辞書が必要な場合は、次のように使用できset_index
ますto_dict
。
In [36]: df2 = df.loc[idx, ['word', 'tag']].set_index('word')
In [37]: df2
Out[37]:
tag
word
a T
an T
the S
In [38]: df2.to_dict()['tag']
Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'}