1

I have

df = pd.DataFrame('data', car, 'ok')

df:

 data               car         ok                                                       
2020-03-25           A            
2020-04-01           A           x
2020-04-15           A              
2020-05-08           A           x
2020-06-25           A           x
2020-06-27           A
2020-07-15         

I want to select last (old in this case) row being column 'ok' with "x"

I want to obtain

2020-04-01   A     x

Thanks!

2
  • sorry old case is : 2020-04-01 A x Commented Sep 27, 2020 at 19:12
  • Is your data sorted by date? Commented Sep 27, 2020 at 20:51

2 Answers 2

4

The head() method on DataFrame can give you the first n rows of a DataFrame. Indexing of a DataFrame will allow you to select rows meeting your filter criteria - to narrow to a subset DataFrame with such rows. Together, you could use them to do:

r = df.loc[df.ok == 'x', :].head(1)

What you are doing here is narrowing to a subset DataFrame where ok is 'x' (the df.loc[df.ok == 'x', :] part), then taking the first row of it (the .head(1) part). This of course assumes the DataFrame is sorted by date as it is above.

Indexing is a huge and fundamental topic (think of it as the SQL WHERE of pandas) so you should spend time gaining a deep knowledge of it. Here is a great tutorial. This one and this one are also good.

Sign up to request clarification or add additional context in comments.

Comments

1

This will work also when your data is not sorted:

df[df.ok == 'x'][df.data == df.data.min()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.