2017-01-06 2 views
1

私は、1つのデータフレームdfを2列(その単語の意味と意味)で構成しています。私は、単語の各定義にCollections.Counterオブジェクトを使用して、可能な限り最も平凡な方法で定義内に出現する単語の頻度を数えたいと思います。データフレームのpythonで列の値を追加する最も効率的な方法を書くには?

従来の方法は、iterrows()メソッドを使用してデータフレームを反復し、計算を行うことでした。

その後、あなたは、単にスペースの分割後definitionシリーズにCounter.mapメソッドを使用し、df 2つの列'word''definition'を持っていると仮定すると、サンプル出力

<table style="height: 59px;" border="True" width="340"> 
 
    <tbody> 
 
    <tr> 
 
     <td>Word</td> 
 
     <td>Meaning</td> 
 
     <td>Word Freq</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Array</td> 
 
     <td>collection of homogeneous datatype</td> 
 
     <td>{'collection':1,'of':1....}</td> 
 
    </tr> 
 
    <tr> 
 
     <td>&nbsp;</td> 
 
     <td>&nbsp;</td> 
 
     <td>&nbsp;</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

答えて

0

。次に結果を合計します。

from collections import Counter 

def_counts = df.definition.map(lambda x: Counter(x.split())) 
all_counts = def_counts.sum() 
+0

おかげでジェームズが...あなたの提案が – user765160

2

私はパンダstrアクセサメソッドを利用して、スペースと使用することで、この

from collections import Counter 
Counter(df.definition.str.cat(sep=' ').split()) 

いくつかのテスト

df = pd.DataFrame({'word': ['some', 'words', 'yes'], 'definition': ['this is a definition', 'another definition', 'one final definition']}) 

print(df) 
      definition word 
0 this is a definition some 
1 another definition words 
2 one final definition yes 

そしてが連結したデータや分割を行うだろうカウンター

Counter(df.definition.str.cat(sep=' ').split()) 

Counter({'a': 1, 
     'another': 1, 
     'definition': 3, 
     'final': 1, 
     'is': 1, 
     'one': 1, 
     'this': 1}) 
+0

テッドPetrouたくさん助け:コメントありがとうございました。 私は、同様の計算を1000の単語の定義のための最も無作為な方法で行う方法も知りたいですか? – user765160

+0

これは、すべての異なる単語サイズのアリの数の定義に対して機能します。 –

+0

つまり、1000の異なる単語、つまりデータフレーム内の1000行について言いたいのですか? – user765160

0

私はこの回答が役に立つと思っていますが、選ばれた答えはありません。実際、私はCounterと@ TedPetrouの答えについてのみ議論しています。

ランダム言葉

a = np.random.choice(list(ascii_lowercase), size=(100000, 5)) 

definitions = pd.Series(
    pd.DataFrame(a).sum(1).values.reshape(-1, 10).tolist()).str.join(' ') 

definitions.head() 

0 hmwnp okuat sexzr jsxhh bdoyc kdbas nkoov moek... 
1 iiuot qnlgs xrmss jfwvw pmogp vkrvl bygit qqon... 
2 ftcap ihuto ldxwo bvvch zuwpp bdagx okhtt lqmy... 
3 uwmcs nhmxa qeomd ptlbg kggxr hpclc kwnix rlon... 
4 npncx lnors gyomb dllsv hyayw xdynr ctwvh nsib... 
dtype: object 

タイミング
Counterの大規模な例を作成速く私は考えることができ、最速より1000倍程度です。

enter image description here

関連する問題