0

I want to create 6 pandas dataframes from 6 text files. I want to name them according to the names of the text files. The text files are named as 'DAPC_min.txt' and so on. I want the dataframe names as 'DAPC_data' and so on.

import pandas as pd

lipids = ['DAPC', 'DIPC', 'DLPC', 'DOPC', 'DPPC', 'POPC']

for lipid in lipids:
    '{}_data'.format(lipid) = pd.read_csv(
        '{}_min.txt'.format(lipid),
        delimiter=' ', names=['bead_type', 'z_min', 'gz_min', 'dGwm'])

But I am getting the following error message:

'{}_data'.format(lipid) = pd.read_csv(
    ^
SyntaxError: can't assign to function call

What I am doing wrong?

anotherone
  • 680
  • 1
  • 8
  • 23
  • You can try using a dictionary. Key is the file name and the DF is the value – Rakesh Jun 14 '18 at 10:52
  • You try to assign the values from the files to a string. What i would suggest is that you use a dict where the file names are the keys and the values well ... the values. – meissner_ Jun 14 '18 at 10:52
  • Possible duplicate of https://stackoverflow.com/questions/13096604/creating-multiple-variables and others – shmee Jun 14 '18 at 10:56
  • I've added a duplicate which does this for excel worksheets. You can use the same for csv files. – jpp Jun 14 '18 at 10:56
  • Can someone please elaborate a bit? Checking the "original" answers only confused me. – anotherone Jun 14 '18 at 11:01
  • 1
    @anotherone Define a dictionary to hold those variables outside the loop, say `dct = {}` and then inside the loop, change the left hand side to: `dct['{}_data'.format(lipid)] = pd.read_csv(...)` The way you are currently doing is possible in some languages (with some hacks in Python too) but using a dictionary in these situations is strongly recommended. – ayhan Jun 14 '18 at 11:12
  • Thank you for the explanation. – anotherone Jun 14 '18 at 11:20

0 Answers0