Viral Parmar
Viral Parmar

Reputation: 488

Converting Datatype "object" to "Float"

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 :

enter image description here

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

Answers (1)

user_stack_overflow
user_stack_overflow

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

enter image description here

Upvotes: 2

Related Questions