添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
for i, df in enumerate(dframes_list, 1): filename_attempt1 = "{}.csv".format(i) filename_attempt2= f"{i}.csv" df.to_save(filename_attempt2)

Expected Output:

file saved: "economy.csv"
file saved: "finance.csv"
file saved: "language.csv"
    
1 个评论
如何产生dframes_list = [economy, finance, language]
python
python-3.x
pandas
for-loop
asd
asd
发布于 2021-02-12
2 个回答
jezrael
jezrael
发布于 2021-02-12
已采纳
0 人赞同

I think in python is strongly not recommended创建字符串变量,因为这时生成的字符串不是琐碎.

那么最好是为字符串中的名字创建另一个列表,并使用zip

dframes_list = [economy, finance, language]
names = ['economy','finance','language']
for i, df in zip(names, dframes_list):
    filename_attempt1 = "df_{}.csv".format(i)

另一个想法是创建DataFrames的dict。

dframes_dict = {'economy': economy, 'finance': finance, 'language': language}
for i, df in dframes_dict.items():
    filename_attempt1 = "df_{}.csv".format(i)

If need working with dict of DataFrames use:

 for k, v in dframes_dict.items():
     v = v.set_index('date')
     #another code for processing each DataFrame
     dframes_dict[k] = v
    
asd
谢谢。我怎样才能更新数据帧或至少更新字典的键?如果我在forloop中做df = df.set_index('date'),当我在forloop之外运行时,没有任何变化。【替换代码1
@asd - 给我一点时间。
@asd - 对答案进行了补充,你需要在最后一步设置dfs的fictionary。
gezibash
gezibash
发布于 2021-02-12
0 人赞同

如果你在笔记本上做这个,你可以使用一个黑客,你搜索locals(),你可以使用regex来匹配'dframes_list = [.+]`,应该返回一个字符串值。

'dframes_list = [economy, finance, language]'

然后你可以做替换,直到你到达 "经济、金融、语言",在这一点上你可以分割并得到一个列表。

合作版的工作方式是这样的。

temp_local = dict(locals())
data = {}
for k,v in temp_local.items():
    if re.match('dframes_list = \[.+\]', v):
      data[k] = v
      print(k, v)
  except: