Reputation: 488
I have been working with a CSV file for the last few days. And What I want is to convert data into float format in CSV in order to round up the last few digits after the decimal point. When I ran Dataframe "dtypes" on a pandas data frame, it turns out the data is neither float or integer. The type of data was object shown in the figure below :
As you can see in the screenshot that few numeric data is in Object format. So I want to know that, how to convert object type to float in python.
Any Information on this will appreciated. Thank you !
Upvotes: 4
Views: 12497
Reputation: 485
Someone else already answered the question in the comments with .astype() … but here is some code to explain it.
Just as a pro tip, please provide starter code to create a sample dataframe to make it easier for people to help you.
import pandas as pd
# step 1: create sample dataframe
df = pd.DataFrame({'strain': ['10.123456789', '10.23456789', '10.3456789'],
'temp': ['1.7', '1.8', '1.9'],
'weight': ['100.4', '100.5', '100.6'],
})
# step 2: examine dataframe and dtypes
print('Dataframe: ')
print(df.head())
print()
print('Dtypes: ')
print(df.dtypes)
print()
# step 3: convert the 'strain' column to float, round to 2 decimal places
df['strain_float'] = df['strain'].astype(float).round(2)
# step 4: examine dataframe and dtypes
print('Dataframe: ')
print(df.head())
print()
print('Dtypes: ')
print(df.dtypes)
print()
df
Upvotes: 2