8

テキストの文字列で呼び出さDataFrameれた列があります。これらの文字列の個々の単語を独自の行で取得し、他の列と同じ値を取得したいと思います。たとえば、3 つの文字列 (および無関係な列、時間) がある場合:pandasdf.strings

    Strings Time
0   The dog  4Pm
1  lazy dog  2Pm
2   The fox  1Pm

文字列の単語を含む新しい行が必要ですが、それ以外は同一の列が必要です

Strings   --- Words ---Time  
"The dog" --- "The" --- 4Pm  
"The dog" --- "dog" --- 4Pm  
"lazy dog"--- "lazy"--- 2Pm  
"lazy dog"--- "dog" --- 2Pm  
"The fox" --- "The" --- 1Pm  
"The fox" --- "fox" --- 1Pm

文字列から単語を分割する方法を知っています:

   string_list  = '\n'.join(df.Strings.map(str))
   word_list = re.findall('[a-z]+', Strings)

しかし、インデックスとその他の変数を保持しながら、どうすればこれらをデータフレームに入れることができますか? Python 2.7 と pandas 0.10.1 を使用しています。

編集:この質問にある groupby を使用して行を展開する方法を理解しました:

def f(group):
    row = group.irow(0)
    return DataFrame({'words':  re.findall('[a-z]+',row['Strings'])})
df.groupby('class', group_keys=False).apply(f)

私はまだ他の列を保持したいと思います。これは可能ですか?

4

1 に答える 1

13

を使用しない私のコードはgroupby()次のとおりです。より高速だと思います。

import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({
"strings":["the dog", "lazy dog", "The fox jump"], 
"value":["a","b","c"]})

w = df.strings.str.split()
c = w.map(len)
idx = np.repeat(c.index, c.values)
#words = np.concatenate(w.values)
words = list(itertools.chain.from_iterable(w.values))
s = pd.Series(words, index=idx)
s.name = "words"
print df.join(s)

3 つの結果:

        strings value words
0       the dog     a   the
0       the dog     a   dog
1      lazy dog     b  lazy
1      lazy dog     b   dog
2  The fox jump     c   The
2  The fox jump     c   fox
2  The fox jump     c  jump
于 2013-03-14T11:19:41.650 に答える