简体   繁体   中英

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM