Is there a possibility to get the first value from a filtered dataframe without having to copy and reindexing the whole dataframe?
Lets say I have a dataframe df:
index | statement | name |
---|---|---|
1 | True | 123 |
2 | True | 456 |
3 | True | 789 |
4 | False | 147 |
5 | False | 258 |
6 | True | 369 |
and I want to get the name of the first row with statement that is False.
I would do:
filtered_df = df[df.statement == False]
filtered_df = reset_index(drop=True)
name = filtered_df.loc[0, "name"]
but is there an easier/faster solution to this?
CodePudding user response:
If it is for the name of the first statement that is False, then use
df[~df.statement].name.iloc[0]
The ~
inverts the selection ("negates"), so only the rows where df.statement
equals False
are selected.
Then the name
column of that selection is selected, then the first item by position (not index) is selected using .iloc[0]
.
CodePudding user response:
The best approach to make your code neat and more readable is to use pandas method chaining.
df.query('statement == False').name.iloc[0]
Generally the .query()
method improves the code readability while performing filtering operations.