shoggananna
shoggananna

Reputation: 565

slicing a dataframe via the startswith method

Input:

df = pd.DataFrame({'A':['jfgh',23,'START',34,42,56], 'B':['cvb',7,'rtwf',65,87,23]})

Output:

       A     B
0   jfgh   cvb
1     23     7
2  START  rtwf
3     34    65
4     42    87
5     56    23

I would like to automatically extract the slice df[3:6]via the startswith method, ie I want to select the index relating to the value 34 and 23.

for index in range(len(df)):
    if df['A'].startswith('START'):
        df1 = df[index+1:len(df)]
        break

but it returns the AttributeError: 'Series' object has no attribute 'startswith'

I thought by selecting df['A'] it returns a series and thus enables the execution of startswith()?

Upvotes: 0

Views: 71

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

Change this:

if df['A'].startswith('START'):

to this:

if str(df.loc[index,'A']).startswith('START'):

Full code:

for index in range(len(df)):
    if str(df.loc[index,'A']).startswith('START'):
        df1 = df[index+1:len(df)]
        break
print(df1)

Output

    A   B
3  34  65
4  42  87
5  56  23

Upvotes: 1

Related Questions