【问题标题】:Use string variable value to define dataframe python- Pandas使用字符串变量值来定义数据框 python- Pandas
【发布时间】:2017-07-09 01:49:17
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    我才发现,似乎需要区分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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2018-02-10
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多