如何在Pandas中用变量来命名数据框

2024-04-27 22:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在熊猫体内产生多个DataFrames? 我想用如下变量命名DataFrames

for i in range 1 to 100
dfi in dfs


df1=
df2=
df3=

:
:
:

df99=
df100=

Tags: toinforrange命名dataframesdf1df2
2条回答

如果确实要创建命名变量,可以执行以下操作

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

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

我想你可以用dict comprehension

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

样品:

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

相关问题 更多 >