lte__ lte__ - 19 days ago 5
Python Question

Python - Get value from pandas dataframe by index condition

I want to get an element out of a dataframe by a condition, like this:

elem = df[(df['id']==enum['properties']['property2']) & (df['time']==10)].col3


Since it's impossible for Python to know if this will return just one or a bunch of rows, it returns this as

6244 52.45
Name: col3, dtype: float64


But I know there's only going to be one element like this. How can I make it so that
elem
only contains
52.45
?

EDIT

The answer by Julien Marrec works fine in a single line, but not in the following loop:

for enum in data['features']:
elem = df[(df['id']==enum['properties']['property2']) & (df['time']==10)].col3.values[0]


It gives me an
IndexError: index 0 is out of bounds for axis 0 with size 0.

Answer

You can just do a quick hack:

elem.values[0]

Update: after the edit to your question, you need to test if there's actually an element to return or if the series is empty:

for enum in data['features']:
    elem = df[(df['id']==enum['properties']['property2']) & (df['time']==10)].col3
    if len(elem) == 1:
        return elem.values[0]
Comments