Read Only First Column of pandas DataFrame in CSV File in Python (Example)
In this Python tutorial you’ll learn how to import only the first column of a CSV file.
Table of contents:
Here’s the step-by-step process:
Example Data & Add-On Libraries
We first have to import the pandas library, in order to use the functions that are contained in the library:
import pandas as pd # Import pandas library
We’ll also have to create some data that we can use in the exemplifying syntax below:
data = pd.DataFrame({'x1':range(1, 9), # Create pandas DataFrame 'x2':[7, 3, 1, 5, 3, 3, 9, 8], 'x3':[5, 2, 5, 1, 4, 1, 4, 7], 'x4':['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']}) print(data) # Print pandas DataFrame
Have a look at the previous table. It shows that our example data consists of eight rows and four columns.
Let’s export these data to a CSV file:
data.to_csv('data.csv') # Export pandas DataFrame
At this point, you should find a new CSV file in your current working directory on your computer. We’ll use this CSV file for the example below.
Let’s continue!
Example: Read Only First Column from CSV File
The following syntax shows how to create a new pandas DataFrame from a CSV file that contains only the very first column of this file.
To achieve this, we have to set the usecols argument within the read_csv function to be equal to [1].
Consider the Python code below:
data_import = pd.read_csv('data.csv', # Read first pandas DataFrame column usecols = [1]) print(data_import) # Print imported pandas DataFrame
In Table 2 you can see that we have created a new pandas DataFrame containing only the first column of our CSV file with the previous code.
Video & Further Resources
In case you need more information on the Python codes of this post, you might want to have a look at the following video on my YouTube channel. In the video, I illustrate the Python programming code of this tutorial in Python.
The YouTube video will be added soon.
Furthermore, you could have a look at some of the related posts on my homepage. A selection of articles is listed here.
- Basic Course for the pandas Library in Python
- Read Only Certain Columns of CSV File as pandas DataFrame
- Read CSV File as pandas DataFrame in Python
- Change Data Type of pandas DataFrame Column in Python
- Drop First & Last N Rows from pandas DataFrame in Python
- Count Unique Values in Column of pandas DataFrame in Python
- Sort pandas DataFrame by Column in Python
- Get Column Names of pandas DataFrame as List in Python
- Python Programming Examples
Summary: In this tutorial you have learned how to read only the first column of a CSV file as a new pandas DataFrame in Python. Don’t hesitate to let me know in the comments section, in case you have additional comments or questions.