2017-08-19 6 views
1

私はPandas DataFrameのテキストデータを別のカラムのフィールドの特定のタグと値に基づいて解析し、それを独自のカラムに格納しようとしています。私はこのデータフレームを作成した場合、DF:私はこのDFを得るようRegex Parsingを使用した新しいPandasカラム

df = pd.DataFrame([[1,2],['A: this is a value B: this is the b val C: and here is c.','A: and heres another a. C: and another c']]) 
df = df.T 
df.columns = ['col1','col2'] 


df['tags'] = df['col2'].apply(lambda x: re.findall('(?:\s|)(\w*)(?::)',x)) 
all_tags = [] 

for val in df['tags']: 
    all_tags = all_tags + val 
all_tags = list(set(all_tags)) 
for val in all_tags: 
    df[val] = '' 

df: 
    col1            col2  tags A C B 
0 1 A: this is a value B: this is the b val C: and... [A, B, C]  
1 2   A: and heres another a. C: and another c  [A, C] 

にはどうすればCOL2からそれらの値を持つ新しい「タグ」列のそれぞれを移入します:

col1            col2   tags \ 
0 1 A: this is a value B: this is the b val C: and... [A, B, C] 
1 2   A: and heres another a. C: and another c  [A, C] 

        A    C     B 
0  this is a value and here is c. this is the b val 
1 and heres another a. and another c 

答えて

4

str.extractall(?P<key>\w+):(?P<val>[^:]*)(?=\w+:|$)正規表現を使用して別のオプション:

正規表現はセミコロンの後半コロンと値の前にキー(?P<key>\w+)をキャプチャ(?P<val>[^:]*) 2のように個別の列keyvalval先読み構文によって制限された次のキー値の組に達するまで:文字と一致しません。(?=\w+:|$);

df.col2.str.extractall(pat) 

enter image description here

をそしてあなたはピボット:

​​

enter image description here


str.extractallが得られます。これは、キーは常に曖昧そうになり、単一の単語であると仮定し結果とwiを連結する元のデータフレームである。

1

ここに1つです道

In [683]: (df.col2.str.findall('[\S]+(?:\s(?!\S+:)\S+)+') 
      .apply(lambda x: pd.Series(dict([v.split(':', 1) for v in x]))) 
     ) 
Out[683]: 
         A     B    C 
0  this is a value this is the b val and here is c. 
1 and heres another a.     NaN and another c 

あなたはjoin

In [690]: df.join(df.col2.str.findall('[\S]+(?:\s(?!\S+:)\S+)+') 
        .apply(lambda x: pd.Series(dict([v.split(':', 1) for v in x])))) 
Out[690]: 
    col1            col2  tags \ 
0 1 A: this is a value B: this is the b val C: and... [A, B, C] 
1 2   A: and heres another a. C: and another c  [A, C] 

         A     B    C 
0  this is a value this is the b val and here is c. 
1 and heres another a.     NaN and another c 
を使用して結果をバック追加することができ

Infactは、あなたはdf['tags']文字列メソッドを使用して

In [688]: df.col2.str.findall('(?:\s|)(\w*)(?::)') 
Out[688]: 
0 [A, B, C] 
1  [A, C] 
Name: col2, dtype: object 

詳細得ることができます:リストリストのキーと値のペアに今

In [684]: df.col2.str.findall('[\S]+(?:\s(?!\S+:)\S+)+') 
Out[684]: 
0 [A: this is a value, B: this is the b val, C: ... 
1   [A: and heres another a., C: and another c] 
Name: col2, dtype: object 

、へ

スプリットグループを。

In [685]: (df.col2.str.findall('[\S]+(?:\s(?!\S+:)\S+)+') 
      .apply(lambda x: [v.split(':', 1) for v in x])) 
Out[685]: 
0 [[A, this is a value], [B, this is the b val... 
1 [[A, and heres another a.], [C, and another c]] 
Name: col2, dtype: object 
関連する問題