pandas 如何用熊猫中的变量命名数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40482738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:23:52  来源:igfitidea点击:

How to name dataframe with variables in pandas

pythonpandasdataframe

提问by Taro Nikkei

Is there a way to generate multiple DataFramesin Pandas? I want to name the DataFrameswith variables like:

有没有办法DataFrames在 Pandas 中生成多个?我想将DataFrames变量命名为:

for i in range 1 to 100
dfi in dfs


df1=
df2=
df3=

:
:
:

df99=
df100=

回答by jezrael

I think you can use dict comprehension:

我认为你可以使用dict comprehension

N = 101 # 5 in sample
dfs = {'name' + str(i):df for i in range(1,N)}
print (dfs)

Sample:

样本:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

N = 5
dfs = {'name' + str(i):df for i in range(1,N)}
print (dfs)
{'name3':    A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3, 'name4':    A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3, 'name2':    A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3, 'name1':    A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3}

print (dfs['name1'])
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

回答by honza_p

If you really want to create named variables, you can do the following

如果你真的想创建命名变量,你可以执行以下操作

variables = locals()
for i in range(100):
    variables["df{0}".format(i)] = ...

But as others suggested, using a dictionary is perhaps better

但正如其他人所建议的,使用字典可能更好