2017-01-17 5 views
4

値がいくつかのstrで始まらない行を選択したいとします。たとえば、パンダdfがあり、データを選択したい場合は、tcで開始しないでください。このサンプルでは、​​出力はmext1okl1である必要があります。パンダでいくつかのstrで始まる行の選択方法は?

import pandas as pd 

df=pd.DataFrame({'col':['text1','mext1','cext1','okl1']}) 
df 

    col 
0 text1 
1 mext1 
2 cext1 
3 okl1 

私はこれ欲しい:あなたは、文字列の機能を取得するにはstrのアクセサを使用することができます

col 
0 mext1 
1 okl1 

答えて

11

を。 getメソッドは、文字列の特定のインデックスを取得できます。

df[~df.col.str.get(0).isin(['t', 'c'])] 

    col 
1 mext1 
3 okl1 

あなたは除外したい値のタプル(とないリスト)と同様startswithを使用することができるように見えます。

df[~df.col.str.startswith(('t', 'c'))] 
+0

をテストするこのソリューションは、私は値を埋めるために新しい列を追加する場合、どのようにより良い1 – ade1e

+0

TKSを、スケール? @Ted Petrou –

6

str.startswithを使用して無効にすることができます。

df[~df['col'].str.startswith('t') & 
     ~df['col'].str.startswith('c')] 

col 
1 mext1 
3 okl1 

それとも@Ted Petrouあたりとしてタプルの複数の文字とのより良いオプション、:

df[~df['col'].str.startswith(('t','c'))] 

    col 
1 mext1 
3 okl1 
+1

複数の値を含むリストではなくタプルで 'startswith'を使うことができるようです。なぜタプルは動作するのですが、リストはありません。 –

+0

ニース、リストを試してみました。タプルはありませんので、@ TedPetrou – ade1e

4

あなたは正規表現を好む場合はちょうど別の代替:

df1[df1.col.str.contains('^[^tc]')] 
+1

ここにラムダは必要ありません –

+0

ああ、ええ、あなたは正しいです –

9

オプション1
str.matchとne

を放送見て前方の

df[df.col.str.match('^(?![tc])')] 

オプション2

df.query('col.str[0] not list("tc")') 

query内でオプション3
numpy gative


  col 
1 mext1 
3 okl1 

時間

def ted(df): 
    return df[~df.col.str.get(0).isin(['t', 'c'])] 

def adele(df): 
    return df[~df['col'].str.startswith(('t','c'))] 

def yohanes(df): 
    return df[df.col.str.contains('^[^tc]')] 

def pir1(df): 
    return df[df.col.str.match('^(?![tc])')] 

def pir2(df): 
    return df.query('col.str[0] not in list("tc")') 

def pir3(df): 
    df[(df.col.str[0][:, None] == ['t', 'c']).any(1)] 

functions = pd.Index(['ted', 'adele', 'yohanes', 'pir1', 'pir2', 'pir3'], name='Method') 
lengths = pd.Index([10, 100, 1000, 5000, 10000], name='Length') 
results = pd.DataFrame(index=lengths, columns=functions) 

from string import ascii_lowercase 

for i in lengths: 
    a = np.random.choice(list(ascii_lowercase), i) 
    df = pd.DataFrame(dict(col=a)) 
    for j in functions: 
     results.set_value(
      i, j, 
      timeit(
       '{}(df)'.format(j), 
       'from __main__ import df, {}'.format(j), 
       number=1000 
      ) 
     ) 

fig, axes = plt.subplots(3, 1, figsize=(8, 12)) 
results.plot(ax=axes[0], title='All Methods') 
results.drop('pir2', 1).plot(ax=axes[1], title='Drop `pir2`') 
results[['ted', 'adele', 'pir3']].plot(ax=axes[2], title='Just the fast ones') 
fig.tight_layout() 

enter image description here

+0

プロット出力を見るにはニース@piRSquaredあなたの記事を読むのが面白い常にサー、 +1 – ade1e

関連する問題