Cyber_Tron
Cyber_Tron

Reputation: 299

Pandas Dataframe How to extract rows of data before a specific row?

I have a dataframe like,

A,B,C
1,2,'Balder'
3,4,'Vasquez'
5,6,'Hatala'
7,8,'Perron'

but the dataframe can also be something like,

A,B,C
1,2,'Balder'
3,4,'Vasquez'
7,8,'Perron'

I want to extract everything before the row,

7,8,'Perron'

for all kinds of dataframes where the above row can appear anytime. It is dynamic and not appearing at a fixed row number!

I have tried skipping the rows in my dataframe using the skiprows variable but it doesn't help for all cases.

df=pd.read_csv('file.csv',skiprows=)

TIA!

Upvotes: 2

Views: 880

Answers (1)

ilyankou
ilyankou

Reputation: 1329

Assuming your index are integer numbers, first find the index of the row that contains your data, then use loc to get all rows before that one.

idx = df[(df.A == 7) & (df.B == 8) & (df.C == 'Perron')].iloc[0].name

subset = df.loc[:idx-1]

subset

>>>
A,B,C
1,2,'Balder'
3,4,'Vasquez'
7,8,'Perron'

Upvotes: 3

Related Questions