1

I have a list files that I want to iterate over and import as dataframes:

data_files = ['data1.csv', 'data2.csv', 'data3.csv']

I'm trying to iterate over the list and create eponymously name dataframes, kind of like doing the following manually:

data1 = pd.read_csv('data1.csv')
data2 = pd.read_csv('data2.csv')
data3 = pd.read_csv('data3.csv')

I tried this:

for i in data_files:
    name = i.split('.')
    name = pd.read_csv(name + ".csv")

The problem with the above is that it's just creating "i" as a dataframe, and not creating a set of eponymous dataframe objects. Can someone help me with this?

Jan
  • 42,290
  • 8
  • 54
  • 79
Daniel
  • 363
  • 3
  • 11

2 Answers2

2

You might be overwriting your dataframe every time you iterate. Use a dictionary / list instead:

dataframes = dict()
for i in data_files:
    name = i.split('.')
    dataframes[name] = pd.read_csv(name + ".csv")

Afterwards, access your dataframe like dataframes['data1'].

Jan
  • 42,290
  • 8
  • 54
  • 79
0

You can create a dictionary in which the data objects are stored:

data_dict = {}
for i in range(len(data_files)):
    data_dict[i] = pd.read_csv(data_files[i])

Also, calling i.split('.') creates a list of the form ['data1','csv'] which I am not sure if that is your intent when you then try and call read_csv, as you are functionally stating read_csv(['data1', 'csv'] + '.csv') which doesn't make sense.

solvador
  • 95
  • 1
  • 10