使用字符串变量值来定义数据帧python-Pandas

时间:2017-02-19 22:03:05

标签: python-3.x pandas jupyter-notebook

我已经生成了很多字符串变量,如下所示

for i in range(10):
    r='df'+str(i)
    r== pd.DataFrame(np.random.rand(4, 5),
                   index=["A", "B", "C", "D"],
                   columns=["I", "J", "K", "L", "M"])

我得到的结果是

TypeError: Could not compare ['df0'] with block values

我期待得到

df0, df1, ... df9

具有相同的索引和列但值不同。

1 个答案:

答案 0 :(得分:0)

我发现它,似乎需要区分2引号:1)'和2)"

在这种情况下使用exec()函数

非常重要
k=[]
for i in range(10):
    r='df'+str(i)
    exec(r + " = pd.DataFrame(np.random.rand(4, 5), index=['A', 'B', 'C', 'D'],columns=['I', 'J', 'K', 'L', 'M'])")
    k.append(r)

观察结果

for i in k:
    print(i)
    print(globals()[i])