Home > Net >  Filter dataframe using startswith twice
Filter dataframe using startswith twice

Time:04-10

I have a dataframe that I want to filter using startswith twice. Something like this

df = df.loc[df['Col'].str.startswith('Foo', na=False) | df['Col'].str.startswith('Bar', na=False)]

But this not work, how can I fix?

CodePudding user response:

There are two ways to solve your problem. The first is to use paranthesis:

df = df.loc[(df['Col'].str.startswith('Foo', na=False)) | (df['Col'].str.startswith('Bar', na=False))]

The second is to make use of the string startswith method, that can take any number of arguments:

df.loc[df['Col'].str.startswith(('foo', 'bar'))]
  • Related