dataframe column cast astype() not casting to float from string

Simple data type conversion

Pandas Data Frame astype() not casting to float.

Error: ValueError: could not convert string to float: 'Temperature'

Effort

Attempted two approaches to string strip() to clean invisible chars from df['Temperature']

df.columns = df.columns.str.strip()
df["Temperature"] = df['Temperature'].str.strip().astype(float)

Even tried astype()

df = df.apply(lambda x: x.astype(np.float64), axis=1)

Still get same ValueError: could not convert string to float: 'Temperature'

Data df['Temperature']

0      29
1      29
2      26
3      25
4      27
       ..
242    30
243    28
244    27
245    24
246    24
Name: Temperature, Length: 245, dtype: object

Upvotes: 0

Views: 634

Answers (1)

Timeless
Timeless

Reputation: 37827

ValueError: could not convert string to float: 'Temperature'

It seems like there is at least one row in the column/series df['Temperature'] that equals to Temperature.

Try to clean up your column before calling pandas.Series.astype :

df["Temperature"] = df['Temperature'].replace('Temperature', np.nan).astype(float)

Or use pandas.to_numeric :

df['Temperature'] = pd.to_numeric(df['Temperature'], errors='coerce')

Upvotes: 1

Related Questions