2017-08-25 3 views
1

Pythonを正しく使用する方法を完全に理解していないので、ここで私の愚かさに耐えてください。python 2つの不等なサイズの列の間で部分文字列を一致させる方法

のは、我々はこのようなデータフレームがあるとしましょう:

samp_data = pd.DataFrame([[1,'hello there',3], 
          [4,'im just saying hello',6], 
          [7,'but sometimes i say bye',9], 
          [2,'random words here',5]], 
          columns=["a", "b", "c"]) 
print(samp_data) 
    a      b c 
0 1    hello there 3 
1 4  im just saying hello 6 
2 7 but sometimes i say bye 9 
3 2  random words here 5 

を、私たちは私たちが望むいけない単語のリストを設定します。

unwanted_words = ['hello', 'random'] 

私はは、すべての行を除外する関数を書きたいですここで、列bには「unwanted_words」リストの単語が含まれています。だから、出力は次のようになります。

print(samp_data) 
    a      b c 
2 7 but sometimes i say bye 9 

は私がこれまで試したものの中に組み込まれて「ISIN()」関数で使用して、次のとおりです

data = samp_data.ix[samp_data['b'].isin(unwanted_words),:] 

を私は期待通り、この行を排除するものではありません。 と私はstr.containsを使用してみました()関数:

for i,row in samp_data.iterrows(): 
    if unwanted_words.str.contains(row['b']).any(): 
     print('found matching words') 

、これは私にエラーをスローしていました。

私は物事を複雑にしていると思うし、私が気づいていない本当に簡単な方法があるはずです。 ご迷惑をおかけして申し訳ございません。 (私はすでに多くのウィンドウを閉じて、このリストに限定されない)私がこれまでに読み込ま

記事:

+0

あなたは「パンダ」との質問にタグを付ける必要があります。これは純粋なPythonではありません。 – glenfant

答えて

1

を使用したい場合があり

a b      c 
2 7 but sometimes i say bye 9 

を取得

samp_data = samp_data[~samp_data.b.str.contains('hello|random')] 

が含まれています。これは、Series.str.containsメソッドを使用します。ただ、それは正規表現を可能にすることを覚えて:

samp_data[~samp_data['b'].str.contains(r'hello|random')] 

結果は次のようになります。

Out [11]: 
    a       b c 
2 7 but sometimes i say bye 9 
+0

うわー、ありがとう!私はあなたのソリューションが一番好きです!私は何を考えていたのかと似ています。 – alwaysaskingquestions

0

どのようにこの1について-ライナー?私は他のpandas愛好家のいくつかが私よりも若干答えが良いと確信しています。

samp_data[~samp_data['b'].apply(lambda x: any(word in unwanted_words for word in x.split()))] 

    a      b c 
2 7 but sometimes i say bye 9 
1
おそらく

ない最もエレガントな私はそれがあなたのために働くだろうと思いますか?

def in_excluded(my_str, excluded): 
    """ 
    (str) -> bool 
    """ 
    for each in my_str: 
     if each in excluded: 
      return True 
    return False 


def print_only_wanted(samp_data, excluded): 
    """ 
    (list, list) -> None 
    Prints each of the lists in the main list unless they contain a word 
    from excluded 
    """ 
    for each in samp_data: 
     if not in_excluded(each, excluded): 
      print each 
1

inを使用して、1つの文字列が別の文字列内にあるかどうかを判断できます。たとえば、"he" in "hello"は、Trueを返します。あなたがしたい行を選択するために、リスト内包とany機能でこれを組み合わせることができます。

df_sub = samp_data.loc[samp_data['b'].apply(lambda x: not(any([badword in x for badword in unwanted_words]))] 
1

あなたはSTRを使用することができます。あなたが不要な単語のリストが長い場合、あなたはあなたが実際にソリューションには本当に近かった

unwanted_words = ['hello', 'random'] 
samp_data = samp_data[~samp_data.b.str.contains('|'.join(unwanted_words))] 
関連する問題