How to convert object to float without causing error?

Question:

I have problem to converting the objects in one column to float. There is no ‘,’ or empty space problem, and when I go through the data one by one, or use a for loop to print the float of each object it is possible, but astype does not work and produce ValueError: could not convert string to float: ‘Null’ error. Do you know why?

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns

df1=pd.read_csv('../input/smart-meters-in-london/halfhourly_dataset/halfhourly_dataset/block_10.csv')

energy=df1.loc[:,"energy(kWh/hh)"]
df1['energy']=energy
df1= df1.set_index("tstp")
df1=df1.drop('energy(kWh/hh)', axis=1)
#this works
for i in df1.loc[:, 'energy']:
    print(float(i))
#but not
df1.energy=df1.energy.astype(float64)
Asked By: Narges

||

Answers:

Have you tried:

df1["energy"] = df1["energy"].astype(float64)
Answered By: Mouse

If you want to get a list out of those values why not use map()? Simply, you can try:

list(map(float, df1.loc[:, 'energy']))

I think this will return a list with the objects in that column as float.
map() returns a map object, so you need list()

Answered By: foally
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.