Pandas: Output dataframe to csv with integers

Given a pandas dataframe, we have to write dataframe to csv with integers. By Pranit Sharma Last updated : October 03, 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 CSV file is generally separated with 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.

Outputting pandas dataframe to csv with integers

We use pandas.DataFrame.to_csv() method to write DataFrame into CSV file. It takes an argument in the form of a DataFrame name which has to be written in CSV file. But here, we have a DataFrame with an int type column and after converting DataFrame into CSV file, the values are stored in float type, and hence we need to convert this dataframe with an int type column.

For this purpose, we will convert the data type of the entire Dataframe to int despite the fact that the values were already in, and then we will create the CSV file.

Let us understand with the help of an example,

Python program for outputting pandas dataframe to csv with integers

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {

# Creating DataFrame
df = pd.DataFrame(d)

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

# Converting dtype of entire dataframe
df = df.astype('int64')

# Converting df to csv file

# Display a msg
print("CSV file created")


The output of the above program is:

Example: Pandas: Output dataframe to csv with integers

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.