简体   繁体   中英

Creating pandas dataframes within a loop

I am attempting to create approximately 120 data frames based upon a list of files and dataframe names. The problem is that after the loop works, the dataframes don't persist. My code can be found below. Does anyone know why this may not be working?

for fname, dfname in zip(CSV_files, DF_names):
    filepath = find(fname, path)
    dfname = pd.DataFrame.from_csv(filepath)

This is a python feature. See this simpler example: (comments show the outputs)

 values = [1,2,3]
 for v in values:
     print v,
 # 1 2 3
for v in values:
    v = 4
    print v, 
# 4 4 4
print values
# [1, 2, 3]
# the values have not been modified

Also look at this SO question and answer: Modifying a list iterator in Python not allowed?

The solution suggestd in the comment should work better because you do not modify the iterator. If you need a name to access the dataframe, you can also use a dictionanry:

dfs = {}
for fname, dfname in zip(CSV_files, DF_names):
    filepath = find(fname, path)
    df = pd.DataFrame.from_csv(filepath)
    dfs[dfname] = df
print dfs[DF_names[1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM