Import CSV File as pandas DataFrame in Python – Read & Load (2 Examples)
In this article you’ll learn how to read a CSV file as a pandas DataFrame in Python.
Preparing the Examples
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
my_df = pd.DataFrame({'A':range(100, 105), # Construct new pandas DataFrame 'B':[9, 3, 7, 1, 2], 'C':['a', 'f', 'c', 'f', 'f'], 'D':range(35, 30, - 1)}) |
my_df = pd.DataFrame({'A':range(100, 105), # Construct new pandas DataFrame 'B':[9, 3, 7, 1, 2], 'C':['a', 'f', 'c', 'f', 'f'], 'D':range(35, 30, - 1)})
import os # Import os |
import os # Import os
os.chdir('C:/Users/Data Hacks/Desktop/example folder') # Specify working directory |
os.chdir('C:/Users/Data Hacks/Desktop/example folder') # Specify working directory
my_df.to_csv('my_df.csv') # Write exemplifying DataFrame to folder |
my_df.to_csv('my_df.csv') # Write exemplifying DataFrame to folder
Example 1: Read pandas DataFrame from CSV File
my_df1 = pd.read_csv('my_df.csv') # Import CSV & print output print(my_df1) # Unnamed: 0 A B C D # 0 0 100 9 a 35 # 1 1 101 3 f 34 # 2 2 102 7 c 33 # 3 3 103 1 f 32 # 4 4 104 2 f 31 |
my_df1 = pd.read_csv('my_df.csv') # Import CSV & print output print(my_df1) # Unnamed: 0 A B C D # 0 0 100 9 a 35 # 1 1 101 3 f 34 # 2 2 102 7 c 33 # 3 3 103 1 f 32 # 4 4 104 2 f 31
Example 2: Read pandas DataFrame from CSV File & Ignore Unnamed Index Column
my_df2 = pd.read_csv('my_df.csv', index_col = [0]) # Import CSV & print output print(my_df2) # A B C D # 0 100 9 a 35 # 1 101 3 f 34 # 2 102 7 c 33 # 3 103 1 f 32 # 4 104 2 f 31 |
my_df2 = pd.read_csv('my_df.csv', index_col = [0]) # Import CSV & print output print(my_df2) # A B C D # 0 100 9 a 35 # 1 101 3 f 34 # 2 102 7 c 33 # 3 103 1 f 32 # 4 104 2 f 31
Further Resources & Related Tutorials
Have a look at the following list of Python programming language tutorials. They focus on topics such as groups, variables, dates, and counting.