Load & Import Multiple CSV Files as pandas DataFrames in Python (Example Code)

In this Python programming article you’ll learn how to import multiple CSV files and combine them into a single pandas DataFrame.

Setting up the Example

import pandas as pd                                                                 # Import pandas library
df_A = pd.DataFrame({'A':range(1, 5),                                               # Construct new pandas DataFrame
                     'B':range(6, 10),
                     'C':range(15, 11, - 1)})
print(df_A)
#    A  B   C
# 0  1  6  15
# 1  2  7  14
# 2  3  8  13
# 3  4  9  12
df_A.to_csv('df_A.csv')                                                             # Write exemplifying DataFrame to folder
df_B = pd.DataFrame({'A':range(11, 15),                                             # Construct new pandas DataFrame
                     'B':range(16, 20),
                     'C':range(25, 21, - 1)})
print(df_B)
#     A   B   C
# 0  11  16  25
# 1  12  17  24
# 2  13  18  23
# 3  14  19  22
df_B.to_csv('df_B.csv')                                                             # Write exemplifying DataFrame to folder
df_C = pd.DataFrame({'A':range(101, 105),                                           # Construct new pandas DataFrame
                     'B':range(106, 110),
                     'C':range(115, 111, - 1)})
print(df_C)
#      A    B    C
# 0  101  106  115
# 1  102  107  114
# 2  103  108  113
# 3  104  109  112
df_C.to_csv('df_C.csv')                                                             # Write exemplifying DataFrame to folder

Example: Reading & Concatenating Three CSV Files in Single pandas DataFrame

df_ABC = pd.concat((pd.read_csv(i) for i in ['df_A.csv', 'df_B.csv', 'df_C.csv']))  # Using for loop
print(df_ABC)
#    Unnamed: 0    A    B    C
# 0           0    1    6   15
# 1           1    2    7   14
# 2           2    3    8   13
# 3           3    4    9   12
# 0           0   11   16   25
# 1           1   12   17   24
# 2           2   13   18   23
# 3           3   14   19   22
# 0           0  101  106  115
# 1           1  102  107  114
# 2           2  103  108  113
# 3           3  104  109  112

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top