【问题标题】:Unpack Dictionary of Dataframes解压数据框字典
【发布时间】:2019-09-27 13:17:27
【问题描述】:

我使用 sqlalchemy 从 PostgreSQL 数据库中读取表,并将它们存储在字典中(键是表名,值是数据框)。我可以一次访问它们,但想扩展解决方案,以便我将给定数据库/模式中的所有表作为 pandas 数据框。我要导入的代码如下:

import os
import pandas as pd
import psycopg2
from sqlalchemy import create_engine

engine = create_engine(os.environ['postgres_credentials'] +'db')
conn = engine.connect()
trans = conn.begin()

#Initialize empty dictionary
frames_dict = {}

#Use loop and pd.read_sql() to read tables from DB
table_names = engine.table_names()
select_template = 'SELECT * FROM {table_name}'

for tname in table_names:
    query = select_template.format(table_name = tname)
    frames_dict[tname] = pd.read_sql(query, conn)

# Close connection
conn.close()

这样就成功获取了table_name:dataframe的key:value。主要目标是能够以它们作为键和数据库中的相同名称引用数据帧(我可以从那里处理数据)。

我尝试了以下方法:

  • 使用 .keys() 和 .values() 创建列表并为分配的列表建立索引
  • 使用 setattr 迭代键和值列表,以将 df 名称(作为字符串,在列表中)分配给相应的数据帧。

我也知道这是对大约四年前的this question 的翻版,但没有给出明确的答案。

如果作为列表的键是:

['name1','name2','name3']

并且值是对应的数据帧,我希望能够运行:

[In] name1
[Out] Col1 |  Col2 | Col3
      --------------------
      foo  |    2  |  a
      bar  |    17 |  b
      ...

感谢大家提供的任何帮助!

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    我能想到的一件事是使用namedtuple from collections

    from collections import namedtuple
    import pandas as pd
    
    supposedly_your_dict = {
        'table_1': pd.DataFrame(columns=['t_1_col_1', 't_1_col_2']),
        'table_2': pd.DataFrame(columns=['t_2_col_1', 't_2_col_2']),
        'table_3': pd.DataFrame(columns=['t_3_col_1', 't_3_col_2'])
    }
    
    DBSnapshot = namedtuple('DBSnapshot', supposedly_your_dict.keys())
    
    db_tables = DBSnapshot(**supposedly_your_dict)
    

    现在您应该能够以您想要的方式访问这些表了。 db_tables.table_1 结果:

    Empty DataFrame
    Columns: [t_1_col_1, t_1_col_2]
    Index: []
    

    【讨论】:

      猜你喜欢
      • 2019-07-13
      • 2020-10-06
      • 2017-05-04
      • 2019-04-12
      • 2021-01-15
      • 2019-02-08
      • 1970-01-01
      • 2018-11-03
      • 2011-11-01
      相关资源
      最近更新 更多