Export Specific Columns in DataFrame to CSV File
Last Updated :
27 Feb, 2024
A data frame is a tabular data structure similar to a spreadsheet. It has rows and columns. CSV (Comma-Separated Values) is a plain text file format used for storing tabular data. Each line in a CSV file represents a row of data, and the values within a line are separated by commas. This article explores two methods for exporting selected columns from a DataFrame to a CSV file: using pandas' to_csv()
method and numpy's savetxt()
function.
Export Specific Columns in DataFrame to CSV File
Below are the two export specific columns In DataFrame to CSV File:
- Using pandas to_csv() method: This method simplifies the process of exporting DataFrame columns to a CSV file, requiring minimal code. Selected columns are exported to a file named 'output.csv', with the index excluded.
- Using numpy savetxt() method: Combining DataFrame column selection with numpy's
savetxt()
function offers efficiency and flexibility in exporting specific columns. Parameters such as delimiter, header, format, and comments allow for customized output.
To learn how to export specific columns in DataFrame to CSV, let's create a dataframe using the following code:
Python3
import pandas as pd
data = {
'Name': ['Disha', 'Shravan', 'Jeetu', 'Ram'],
'Age': [21, 23, 24, 22],
'Gender': ['Female', 'Male', 'Male', 'Male'],
'Education': ['Graduation','Masters','Masters','Graduation'],
'Salary':[22000,35000,35000,22000]
}
df = pd.DataFrame(data)
df
Output:
Name Age Gender Education Salary
0 Disha 21 Female Graduation 22000
1 Shravan 23 Male Masters 35000
2 Jeetu 24 Male Masters 35000
3 Ram 22 Male Graduation 22000
Using pandas to_csv() method
This method exports selected DataFrame columns to a CSV file. It's simple and efficient, requiring very less code to specify columns and file path.
- The selected columns will be exported to a CSV file named 'output.csv' using the
to_csv
method. - The
index=False
argument ensures that the index column is not included in the output file.
Python3
df.to_csv('output.csv', columns=['Name','Age','Salary'],index=False)
Let's read the csv column to check.
Python3
df1= pd.read_csv('output.csv')
df1
Output:
Name Age Salary
0 Disha 21 22000
1 Shravan 23 35000
2 Jeetu 24 35000
3 Ram 22 22000
Using numpy savetxt()
This code snippet combines DataFrame column selection with NumPy's np.savetxt
function to efficiently export specific columns from a DataFrame to a CSV file, handling different data types and formatting the output as desired.
delimiter
: The character to separate values in the CSV file.header
: A string containing the header row with column names. It uses string formatting (','.join(desired_columns)
) to create a comma-separated list of column names from the desired_columns
list.fmt
: A format string where '%s'
ensures all data is converted to strings, avoiding potential issues with different data types.comments
: An empty string (''
) to disable comments in the output file.
Python3
import numpy as np
desired_columns = df[['Age','Education','Salary']]
np.savetxt(
"output.csv",
desired_columns,
delimiter=',',
header=','.join(desired_columns),
fmt='%s', # to convert all datatypes to strings
comments='' # this part is necessary to avoid necessary comments like #
)
Let's read the csv column to check.
Python3
df1=pd.read_csv('output.csv')
df1
Output:
Age Education Salary
0 21 Graduation 22000
1 23 Masters 35000
2 24 Masters 35000
3 22 Graduation 22000
Similar Reads
Export Pandas dataframe to a CSV file When working on a Data Science project one of the key tasks is data management which includes data collection, cleaning and storage. Once our data is cleaned and processed itâs essential to save it in a structured format for further analysis or sharing.A CSV (Comma-Separated Values) file is a widely
2 min read
How to export Pandas DataFrame to a CSV file? Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. DataFrame.to_csv() Syntax : to_csv(parameters) Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of
3 min read
How to Export DataFrame to CSV in R ? R Programming language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to Export DataFrame to CSV file in R Programming Language. Approach:Â Write Data in column wise formatCreate DataFrame for these dataWrite Data to the CS
1 min read
Exporting Pandas DataFrame to JSON File Pandas a powerful Python library for data manipulation provides the to_json() function to convert a DataFrame into a JSON file and the read_json() function to read a JSON file into a DataFrame.In this article we will explore how to export a Pandas DataFrame to a JSON file with detailed explanations
2 min read
How to Get Column Names in Pandas Dataframe While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform certain operations. The simplest way to get column names in Pandas is by using the .columns attribute of a DataFrame. Let's understand with a quick example:Pythonimpo
4 min read
Select Columns with Specific Data Types in Pandas Dataframe In this article, we will see how to select columns with specific data types from a dataframe. This operation can be performed using the DataFrame.select_dtypes() method in pandas module. Syntax: DataFrame.select_dtypes(include=None, exclude=None)Parameters :Â include, exclude : A selection of dtypes
2 min read