'How to change the data format to one column and export as csv in Python and Pandas

The picture is just an example and I hope to change this data(str type) to one column (float type) and save as csv in Python. Pandas or Numpy may help but I don't know how to do that. Could someone help me please? Thank you very much.

data example



Solution 1:[1]

To convert as float, you just need to use astype method in your dataframe, and to save it as csv you just need to use to_csv method for your dataframe.

Here's the example of your case:

import pandas as pd

df = pd.DataFrame({"String_type":["2.1","4","5.2"]})

# convert string to float
df["float_type"] = df["String_type"].astype(float)

# save as csv, change out.csv to your filename
df.to_csv('out.csv')

print(df.dtypes)

Hope this would be helpful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Felix Filipi