2016-09-15 6 views
1

私はすべてのリターンマッチを与えられた範囲で取得するために私のコードを使いこなしています。私のデータサンプルは、次のとおりです。正規表現を使って与えられた範囲で結果を一致させるには?

 comment 
0  [intj74, you're, whipping, people, is, a, grea... 
1  [home, near, kcil2, meniaga, who, intj47, a, l... 
2  [thematic, budget, kasi, smooth, sweep] 
3  [budget, 2, intj69, most, people, think, of, e... 

私は結果を取得したいと:私のコードがある(与えられた範囲はintj75するintj1です)

  comment 
0  [intj74] 
1  [intj47]  
2  [nan] 
3  [intj69] 

df.comment = df.comment.apply(lambda x: [t for t in x if t=='intj74']) 
df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]] 

私は」正規表現を使ってt == 'range'の範囲を見つける方法がわかりません。これを行う他のアイデアか?事前に

おかげで、

パンダのPython初心者

+0

'intj \ d +'は、その後に1つ以上の数字が続く 'intj'にマッチします。 – Maroun

+0

@Maroun Marounは返信してくれてありがとう。残念ながら、それは動作していません。あなたの提案をどのように正確に適用するには? –

答えて

1

あなたと[t for t in x if t=='intj74']、例えば、

[t for t in x if re.match('intj[0-9]+$', t)] 

あるいは

[t for t in x if re.match('intj[0-9]+$', t)] or [np.nan] 

もケースの場合を扱うでしょう置き換えることができます一致するものはありません(そのため、チェックする必要はありませんこれは明示的にdf.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]]を使用しています)。ここでの "トリック"は、空のリストがFalseと評価され、その場合にorがその右オペランドを返すことです。

+0

Yess !!! import re、solution re.match( 'intj [0-9] + $'、t)はうまくいきます。とてもありがとう@ewcz –

+0

そしてもう一度、 "トリック"のための@ewczを共有しました。私は試してみましたが、それはうまくいって、私のコードを短くしました。 –

0

私はpandasも新規です。 DataFrameを別の方法で初期化した可能性があります。とにかく、これは私が持っているものです:

import pandas as pd 

data = { 
    'comment': [ 
     "intj74, you're, whipping, people, is, a", 
     "home, near, kcil2, meniaga, who, intj47, a", 
     "thematic, budget, kasi, smooth, sweep", 
     "budget, 2, intj69, most, people, think, of" 
    ] 
} 
print(df.comment.str.extract(r'(intj\d+)')) 
+0

.str.extractを提案していただき、ありがとうございます。これは別の方法です。しかし、私はFutureWarningを取得します:現在の抽出(展開=なし)は、展開= False(インデックス/シリーズ/ DataFrameを返します)を意味しますが、将来のバージョンのパンダではexpand = True(返されるDataFrame)に変更されます if __name__ == '__main__ ':。すべての結果はNaNでした。 –

+0

あなたは明示的で、展開引数を渡すことができます: 'df.comment.str.extract(r '(intj \ d +)'、expand = True)'。 TrueはDataFrameを返します。 FalseはSeriesを返します。あなたに合ったものを使いましょう。 –

+0

ああ、私は参照してください。解説ありがとう@arvindpdmn –

関連する問題