-1

Trying to convert object to float type for labour and material cost.

data type:

Cntr No                         object
Amount in Estimate Currency    float64
Labour Cost                     object
Material Cost                   object
type                            object
dtype: object

output data:

OddU 6167142    543.42  192 351.42  

input : No luck with below code

 #convert to float
 df_co.iloc[:,2:3].apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))
 df_co['Labour Cost'].astype(float)
okl
  • 317
  • 3
  • 12

1 Answers1

1

Unfortunately there is bug, so after assign back float columns are converted to object again:

So possible solution is:

np.random.seed(2018)

np.random.seed(123)
df_co = pd.DataFrame(np.random.choice(['sa5', 's7s'], size=(5, 4)))
print(df_co)
     0    1    2    3
0  sa5  s7s  sa5  sa5
1  sa5  sa5  sa5  s7s
2  s7s  sa5  s7s  s7s
3  sa5  s7s  sa5  s7s
4  sa5  s7s  s7s  sa5

c = df_co.columns[2:3]
print (c)

#remove columns which need convert
df = df_co.drop(c, axis=1)
#convert columns
df1 = df_co[c].apply(lambda x : x.str.extract('(\d+)',expand=False)).astype(float)
#join together and last reindex for same ordering 
df_co = df.join(df1).reindex(columns=df_co.columns)
print(df_co)
     0    1    2    3
0  sa5  s7s  5.0  sa5
1  sa5  sa5  5.0  s7s
2  s7s  sa5  7.0  s7s
3  sa5  s7s  5.0  s7s
4  sa5  s7s  7.0  sa5

print(df_co.dtypes)
0     object
1     object
2    float64
3     object
dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252