Luis
Luis

Reputation: 1475

How to force specific column type in Dataframe?

I have the following code:

import pandas as pd

dic = {"rates":{
   "IT":{
     "country_name":"Italy",
     "standard_rate":20,
     "reduced_rates":{
       "food":13,
       "books":11
     }
  },

   "UK":{
     "country_name":"United Kingdom",
     "standard_rate":21,
     "reduced_rates":{
       "food":12,
       "books":1
     }
  }  
}}

df = pd.DataFrame([{'code': k, 'standard_rate': v["standard_rate"]} for k,v in dic["rates"].items()])
print(df)

Which gives:

  code    standard_rate
0   IT           20
1   UK           21

How can I force standard_rate to be float type?

Note: I know how to print it as float. This is not what I want. I want to change the type of the column in the dataframe itself. So if I export it to csv to Json the value in the standard_rate will be float.

Upvotes: 1

Views: 47

Answers (1)

jezrael
jezrael

Reputation: 863226

Cast it in list comprehension:

comp=[{'code': k, 'standard_rate': float(v["standard_rate"])} for k,v in dic["rates"].items()]
df = pd.DataFrame(comp)
print (df)
  code  standard_rate
0   IT           20.0
1   UK           21.0

Upvotes: 3

Related Questions