lucky1928
lucky1928

Reputation: 8841

pandas - slice dataframe with condition of end point

I would like to use a search result as end point to slice a dataframe.

import pandas as pd

df = pd.DataFrame({'A':['apple','orange','bananna','watermelon'],'B':[1,2,3,2]})
print(df)
pos = df[df['A'].str.contains('ban')]
print(pos)

:             A  B
: 0       apple  1
: 1      orange  2
: 2     bananna  3
: 3  watermelon  2
:          A  B
: 2  bananna  3

for below example, I would like to get output from first row to row start with 'ban', as below:

:             A  B
: 0       apple  1
: 1      orange  2
: 2     bananna  3

Upvotes: 0

Views: 127

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24314

You can use boolean masking and .index attribute:

condition=df[df['A'].str.contains('ban')].index[-1]

Now finally use loc[] accessor or iloc[] accessor:

result=df.loc[:condition,:]

OR

result=df.iloc[:condition+1,:]

Now if you print result you will get:

    A           B
0   apple       1
1   orange      2
2   bananna     3

Upvotes: 1

AnkRaw
AnkRaw

Reputation: 217

Here is the traditional method to do this:

lst = []
for row in df.iterrows(): 
    lst.append(list(row[1])) # Appendig every row as list in temporary list
    if str(row[1][0]).startswith('ban'): # Condition
        break
new_df = pd.DataFrame(lst)
print(new_df)

Output:

         0  1
0    apple  1
1   orange  2
2  bananna  3

:)

Upvotes: 0

Related Questions