F_F
F_F

Reputation: 21

pandas select FROM .... TO

I have a dataframe

C  V  S  D LOC
1  2  3  4  X  
5  6  7  8  
1  2  3  4  
5  6  7  8  Y
9  10 11 12 

how can i select rows from loc X to Y and inport them in another csv

Upvotes: 0

Views: 67

Answers (2)

jezrael
jezrael

Reputation: 862521

Use idxmax for first values of index where True in condition:

df = df.loc[(df['LOC'] == 'X').idxmax():(df['LOC'] == 'Y').idxmax()]
print (df)
   C  V  S  D  LOC
0  1  2  3  4    X
1  5  6  7  8  NaN
2  1  2  3  4  NaN
3  5  6  7  8    Y

Upvotes: 3

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

In [133]: df.loc[df.index[df.LOC=='X'][0]:df.index[df.LOC=='Y'][0]]
Out[133]:
   C  V  S  D  LOC
0  1  2  3  4    X
1  5  6  7  8  NaN
2  1  2  3  4  NaN
3  5  6  7  8    Y

PS this will select all rows between first occurence of X and first occurence of Y

Upvotes: 2

Related Questions