Output different precision by column with pandas.DataFrame.to_csv()?

Learn, how to output different precision by column with pandas.DataFrame.to_csv()? By Pranit Sharma Last updated : October 06, 2023

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.

Suppose that we are given a DataFrame that contains some float values and we need to convert it into a CSV file while maintaining the float precision in the CSV file. We can change the type of specific column before exporting the data frame to a CSV file.

Let us understand with the help of an example,

Python program to output different precision by column with pandas.DataFrame.to_csv()

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame({'A':[1,5,10],'B':[2.44,7.123,12.3542435],'C':[3,8,13],'D':[4,9,14]})

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

# Setting the float precision for column B
df['B'] = df['B'].map(lambda x: '%2.1f' % x)

# Converting df into csv
df.to_csv('hello', index=False, header=False, float_format='%11.6f')

# Export csv file
csv = pd.read_csv('hello')

# Display result
print("New Data:\n",csv)

Output

The output of the above program is:

Example: Output different precision by column with pandas.DataFrame.to_csv()?

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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