How to get a numeric value from Pandas DataFrame?

Question:

I have a Pandas data frame, attack_probability_df:

    city        date        attack probability
0   Rome      1996-02-23    0.163317
1   Rome      1996-02-24    0.219221
2   Rome      1996-02-25    0.180625
3   Rome      1996-02-26    0.149749
4   Rome      1996-02-27    0.121288

I use attack_probability_df.loc[attack_probability_df.date == date].loc[attack_probability_df.city == city]["attack probability"] to extract attack probability by needed date and city, but my code returns this:

2345    0.18593
Name: attack probability, dtype: float64

instead of numeric value. How can I extract the value itself?

Asked By: eresque-

||

Answers:

Just add .values[0] on the end to get the attack_probability.

Answered By: cmauck10

The answer by cmauck10 answers the question keeping the syntax suggested in the question.

Here is an another way (known as boolean indexing) to get attack_probability without using .loc:

df:

   city        date  attack probability
0  Rome  1996-02-23            0.163317
1  Rome  1996-02-24            0.219221
2  Rome  1996-02-25            0.180625
3  Rome  1996-02-26            0.149749
4  Rome  1996-02-27            0.121288

Query:

c = "Rome"
d = "1996-02-25"

Solution:

print(df[(df['city'] == c) & (df['date'] == d)]["attack probability"].values[0])

which gives 0.180625.

Answered By: medium-dimensional
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.