Home > Mobile >  Pandas object could not convert string to float
Pandas object could not convert string to float

Time:04-02

I got some depth image data in csv format.

I want to convert the data into float type so I can reshape them to image

and I get this error enter image description here

my code is like this (I excluded the variables that includes my directory)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


# The name of the column I want to convert is "data"
df = pd.read_csv(img)
dat_float = df['data'].apply(lambda x: x.replace(',','').replace('[','').replace(']','')).astype('float')
print(dat_float)

My dataframe is like this enter image description here

since this is hard to see so I pull out the data I need

enter image description here

The target to change to float from object is the data (right one to the 'seq')

CodePudding user response:

import pandas as pd

# create sample data
data = "0;[0,0,13,3,2,251,2,252]"
df = pd.read_csv(io.StringIO(data), sep=";", header=None)
df.columns = ['seq', 'data']

# convert object to list
df.data=df.data.apply(lambda s: [float(x.strip(' []')) for x in s.split(',')])

# optional: explode to rows
df.explode('data')

CodePudding user response:

For the part that you need to turn your string into float, here's how you can do it. I just make myself a dataframe with a list of strings.

data = {'seq': [1,2],
        'data':[['0','0','0','0','0'],['0','0','0','0','0']]}
df=pd.DataFrame(data)

   seq             data
0    1  [0, 0, 0, 0, 0]
1    2  [0, 0, 0, 0, 0]

And by using list comprehension, you can get what you need.

df['data']=[[float(x) for x in i] for i in df['data']]

   seq                       data
0    1  [0.0, 0.0, 0.0, 0.0, 0.0]
1    2  [0.0, 0.0, 0.0, 0.0, 0.0]
  • Related