0

I added two strings together and now I want to use those strings to create multiple dataframes.... I currently have:

filepath = 'C:/........GC results/lng_11169_fid00'

l = []

for i in range(1,7):
    newpath = filepath + str(i)
    l.append(newpath)

print l 



d =[]

for i in range(1,7):
    dataframes = "df" + str(i)
    d.append(dataframes)
print d
enter code here



m = []
dfstr = "pd.DataFrame.from_csv("

for i in d:
    for x in l:
        newdf =  i + "="+ dfstr + x + ", index_col = None)"
        m.append(newdf)
print m

out:

['df1=pd.DataFrame.from_csv(C:...lng_11169_fid001, index_col = None)', 'df2=pd.DataFrame.from_csv(C:...lng_11169_fid002, index_col = None)'..... + 20 others]

I want to use those strings to make a DataFrame. Is this possible?

3
  • You will find this information useful. Commented Jun 10, 2015 at 9:39
  • @Trimax but this is about calling an internal Python command, isn't it? Commented Jun 10, 2015 at 9:39
  • @SuperBiasedMan You're all right. He wants to execute code dinamically. Commented Jun 10, 2015 at 9:47

2 Answers 2

1

An XY problem... Is this what you want? Simply write executable code instead of string concatenation.

import glob
import pandas as pd
path_pattern = 'C:/........GC results/lng_11169_fid00*'
files = glob.glob(path_pattern)
dataframes = [pd.DataFrame.from_csv(f, index_col=None) for f in files]
print dataframes[0]  # yours df1
Sign up to request clarification or add additional context in comments.

2 Comments

Will this find _fid_001 to _012? and then create a dataframe from each csv?
Yes it does.. Many thanks for this simple yet powerful answer!
0

This should work

list_ = ['df1=pd.DataFrame.from_csv(C:...lng_11169_fid001, index_col = None)', 'df2=pd.DataFrame.from_csv(C:...lng_11169_fid002, index_col = None)'..... + 20 others]

for code_ in list_:
     exec code_

2 Comments

exec is a potentially dangerous command to call, I wouldn't just suggest someone use it without explaining what it does.
This does not work in python3 either, you need to do - exec(code_)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.