float64 with pandas to_csv

Learn, how to save a dataframe of float values into a csv file without the conversion of format of float values?
Submitted by Pranit Sharma, on January 03, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

CSV files or Comma Separated Values files are plain text files but the format of CSV files is tabular. As the name suggests, in a CSV file, each specific value inside the CSV file is generally separated by a comma. The first line identifies the name of a data column. The further subsequent lines identify the values in rows.

Col_1_value, col_2_value , col_3_value
Row1_value1 , row_1_value2 , row_1_value3
Row1_value1 , row_1_value2 , row_1_value3

Here, the separator character (,) is called a delimiter. There are some more popular delimiters. E.g.: tab(\t), colon (:), semi-colon (;) etc.

Saving a dataframe of float values into a csv

To save float values into CSV files, we will use pandas.DataFrame.to_csv() method inside which we will pass an argument float_format='%.3f' so that the size of float values would not change.

Let us understand with the help of an example,

Python program for 'float64 with pandas to_csv'

# Import pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame({'A':['a','b','c','d'], 'B':[0.323,2.343,3.532,8.342]})

# Display original dataframe
print("Original DataFrame:\n",df,"\n")

# Saving df as csv
df.to_csv('pandasfile.csv', float_format='%.3f')

# Display the stored csv file
print("Data if csv file:\n",pd.read_csv('pandasfile.csv'),"\n")

Output

The output of the above program is:

Example: float64 with pandas to_csvframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.