2016-05-05 2 views
-3

私は次のコードを理解するのに助けが必要です。完全なコードのマップ機能は何を説明できますか?

df_all['search_term'] = df_all['search_term'].map(lambda x:str_stemmer(x)) 

リンク:https://www.kaggle.com/wenxuanchen/home-depot-product-search-relevance/sklearn-random-forest/code
はありがとうございます。

+0

'str_stemmer'の定義を見ずに言うのは難しいですか?基本的にはあなたの列の各要素に 'str_stemmer'を呼び出します。' search_term'' – EdChum

+0

http://stackoverflow.com/questions/10973766/understanding-the-map-function –

+1

[docs](http:// pandas。 pydata.org/pandas-docs/stable/generated/pandas.Series.map.html)は例を挙げていますが、あなたの理解が不足しているかどうかはわかりません – EdChum

答えて

2

pandas.Series.mapは、Pythonのマップとは少し異なります。

はあなたには、いくつかの一般的に使用される言葉のルーツを保持している小さな辞書を持っていると仮定します

roots_dict = {"going": "go", "went": "go", "took": "take", "does": "do", 
       "thought": "think", "came": "come", "begins": "begin"} 

あなたはまた、パンダのデータフレームを持っており、そのデータフレームにあなたが単語の列を持っている:

df = pd.DataFrame({"word": ["took", "gone", "done", "begins", "came", 
          "thought", "took", "went"]}) 

     word 
0  took 
1  gone 
2  done 
3 begins 
4  came 
5 thought 
6  took 
7  went 

これらの単語のルーツを示す追加の列が必要な場合は、mapを使用できます。その系列(列)内の各要素について、mapはその単語が辞書内のキーとして存在するかどうかを調べます。存在する場合は、値を返します。それ以外の場合はNaNを返します。代わりに辞書の

df["root"] = df["word"].map(roots_dict) 

     word root 
0  took take 
1  gone NaN 
2  done NaN 
3 begins begin 
4  came come 
5 thought think 
6  took take 
7  went  go 

、あなたもシリーズを渡すことができます。その場合、系列のインデックスをチェックします。

あなたの例では、それは関数で動作します。この関数は、文字列(おそらくいくつかの単語を含む)を取り出し、小文字に変換し、単語に分割し、NLTKのSnawball Stemmerを各単語に適用するように設計されています。したがって、df_all['search_term'].map(lambda x: str_stemmer(x))の場合、 "search_term"列の各行(xはその行の文字列)はstr_stemmer()への入力です。.mapは、その関数が返す要素を結合し、すべての単語の根を持つ別の系列を返します。

+0

ayhanありがとうございます。私は[link](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.apply.html)からもフォローアップしました。 'lambda'は、その末尾に関連する単語の辞書を作成する無名関数です。この辞書はパラメータとしてマップ関数に渡されます。 @ayhan – sbk23

2

私は他の質問を見て、実際にあなたの質問を説明していないようです - mapの機能は何ですか?

mapは、反復可能関数と関数を取り、反復可能関数内のすべての要素に順番に関数を適用します。

はここでの例です:私たちはmapに、最後に()なく、機能の名前を渡している

def square_the_things(value): 
    print('Squaring {}'.format(value)) 
    return value * value 


items = [1,2,3,4,5] 
squared_items = map(square_the_things, items) 

for squared in squared_items: 
    print('Squared item is: {}'.format(squared)) 

出力

Squaring 1 
Squared item is: 1 
Squaring 2 
Squared item is: 4 
Squaring 3 
Squared item is: 9 
Squaring 4 
Squared item is: 16 
Squaring 5 
Squared item is: 25 

注意。ラムダは名前のない関数です。あなたの場合、実際には.map(str_stemmer)を渡すことができます。なぜなら、1つの引数しかないからです。

私の例を見ると、最初の出力が関数Squaring 1から来ていることが分かります。その後、ループの最初の反復を経て、Squared item is: 1と表示されます。それは私がPython3を使用しており、mapがイテレータであるからです。それは反復可能最初以上の関数を適用し、リストを生成しているためだ

Squaring 1 
Squaring 2 
Squaring 3 
Squaring 4 
Squaring 5 
Squared item is: 1 
Squared item is: 4 
Squared item is: 9 
Squared item is: 16 
Squared item is: 25 

:Python2では、それは別の何かを出力します。

+0

これは通常、あなたが質問を間違って読んでいると言いますこの場合、尋問者はそれを書いています。 –

関連する問題