0

I'm trying to save the values from populatioEst column in float variables using Python3 & Pandas, I have the following table:

Name populationEst
Amsterdam 872757
Netherlands 17407585

I have tried to separate both values as following,

populationAM = pops['populationEst'][pops.Name == 'Amsterdam']
populationNL = pops['populationEst'][pops.Name == 'Netherlands']

However when I try to print out the value,print(populationAM), I get this output

0    872757
Name: PopulationEstimate2020-01-01, dtype: int64

and I think that populationAM & populationNL are not int values, because Whenever I try to run some arithmetic operation on them I do not get the desired value.

For example, I have tried to calculate the fraction of the populationAM against populationNL using this formula

frac = populationAM.astype(float) * 100 / populationNL.astype(float)

and I did not get the desired output that should be 5,013659276 but I have got this one:

0 Nan
1 Nan
Name: PopulationEst, dtype: float64

Can Anybody tell where am I going wrong here or how can I save these values in simple float variables.

3 Answers 3

0

Is this what are you looking for?

populationAM = pops.loc[pops.Name == 'Amsterdam', 'populationEst'].iloc[0]
populationNL = pops.loc[pops.Name == 'Netherlands', 'populationEst'].iloc[0]
frac = populationAM * 100 / populationNL

The value of frac here is 5.013659275539944, while populationAM and populationNL are the integers corresponding to the respective populations (as you can see, the type of these variables is not a problem to compute the correct value of frac). In your code, the issue is that populationAM and populationNL are pandas Series, instead of integers; iloc[0] retrieves the value in the first position of the series.

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

Comments

0

Is this what you are trying to do?:

populationAM = pops[pops['pops.Name'] == 'Amsterdam']['populationEst']
populationNL = pops[pops['pops.Name'] == 'Netherlands']['populationEst']

1 Comment

No that will separate the whole row actually, this is like saying: SELECT * FROM pops WHERE pops.Name == Amsterdam, What I have done is more like: SELECT populationEst FROM pops WHERE pops.Name == Amsterdam because pops['populationEst'] on its own is a sub dataframe.
0

Maybe you try this:

    populationAM = pops['populationEst'][pops['Name'] == 'Amsterdam']
    populationNL = pops['populationEst'][pops['Name'] == 'Netherlands']

It will be dtype: Int. But you could easily trnasform it to float.

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.