2017-06-28 2 views
1

私はパンダのデータフレームdfdataの中に文字列データを持つフィールド "fieldname"と、 "then value"のような部分文字列エントリを持っています。私はこれらのエントリを "then value end"のようなものに置き換えたいと思います)。問題は、 "値"が異なる行で異なっており、文字列に複数の ")"が含まれていることです。だからstr.replaceは動作しません。私は多分ワイルドカードでre.subのような何かを考えていたが、私はワイルドカードの値が交換に表示する必要があります。私はループを書く必要があると思っていた。誰かがこれを行うための滑らかな方法を知っていますか?私は以下の例のデータと出力を持っています。パンダパターンマッチングテキストを追加

Example Data: 

import pandas as pd 
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'], 
        'fieldname2': ['Other words when spaghetti then turnip), do this)', 'Different other words when tomato then ketchup)']}) 

Example Output: 

import pandas as pd 
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'], 
        'fieldname2': ['Other words when spaghetti then turnip end), do this)', 'Different other words when tomato then ketchup end)']}) 
+0

テキスト/ CSV形式で設定し、所望の出力データは – MaxU

+0

@MaxUはそうすぐに私に戻ってきてくれてありがとうセット小さなサンプルデータを提供してください。元の投稿を編集し、サンプルデータと出力を追加しました。 – ndderwerdo

答えて

2

IIUC:

In [36]: dfdata['fieldname2'] = \ 
      dfdata['fieldname2'].str.replace(r'(\s*then\s*)(\w+)\)', r'\1\2 end)') 

In [37]: dfdata 
Out[37]: 
    fieldname1            fieldname2 
0  Bob Other words when spaghetti then turnip end), do this) 
1  Jane Different other words when tomato then ketchup end) 
+0

ありがとう、それはトリックでした! – ndderwerdo

+0

@ndderwerdo、うれしい – MaxU

関連する問題