How to select lines that do not start with any line in pandas?

I want to select strings whose values ​​do not start with some str. For example, I have pandas df, and I want the data not to start with tand c. In this example, the output should be mext1and okl1.

import pandas as pd

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

    col
0   text1
1   mext1
2   cext1
3   okl1

I want it:

    col
0   mext1
1   okl1
+4
source share
4 answers

You can use the str accessory to get string functions. The method getcan capture the specified row index.

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

     col
1  mext1
3   okl1

It looks like you can also use startswithwith a tuple (not a list) of values ​​that you want to exclude.

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

1
str.match

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

2
query

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

3
numpy

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

         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

+9

You can use str.startswithand cancel it.

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

col
1   mext1
3   okl1

Or a better option, with multiple characters in a tuple according to @Ted Petrou:

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

    col
1   mext1
3   okl1
+6
source

Another alternative if you prefer regex:

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

Source: https://habr.com/ru/post/1666977/


All Articles