Home > Back-end >  create dataframes with different names with pd. read_csv and for loop
create dataframes with different names with pd. read_csv and for loop

Time:06-26

import pandas as pd
import os
path=r"C:\Users\berid\OneDrive\Desktop\mydata\covid19 South Korea\\"
for file in os.listdir(path):
    print(file)

output:

enter image description here

I want to create dataframes with the same names as csv files.

for file in os.listdir(path):
    name=file.split(".csv")[0]
    name=pd.read_csv(path file)

This creates dataframe with the name "name". I want dataframes names to be "Case","PatientInfo","Policy",etc.

CodePudding user response:

Use:

for file in os.listdir(path):
    name=file.split(".csv")[0]
    df=pd.read_csv(path file)
    exec("%s = df" % (name))

Demonstration:

name = 'ali'
df = pd.DataFrame([1,2,3])
exec("%s = df" % (name))

Output:

ali

    0
0   1
1   2
2   3

CodePudding user response:

this should help create the dataframes...

for file in os.listdir(path):
    name=file.split(".csv")[0]
    exec('{} = pd.read_csv(\'{}\')'.format(name, file))
  • Related