简体   繁体   English

在循环中创建熊猫数据框

[英]Creating pandas dataframes within a loop

I am attempting to create approximately 120 data frames based upon a list of files and dataframe names. 我试图根据文件和数据框名称的列表创建大约120个数据框。 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. 这是python功能。 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? 还要看看这个SO问题和答案: 不允许在Python中修改列表迭代器吗?

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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