【问题标题】:Move data from dataframe to vertica without staging将数据从 DataFrame 移动到 Vertica 而无需暂存
【发布时间】:2023-02-26 11:10:32
【问题描述】:

我正在尝试将数据从数据帧推送到 vertica 表中,目前我将数据暂存到 CSV 中并使用 COPY 命令将数据插入到最终的 vertica 表中。 有没有办法避免将数据暂存到 CSV 或临时表中的中间步骤,而是直接从数据帧移动到 vertica 表?

当前的:

df.to_csv(我的文件) vertica_cursor.copy( "COPY vertica_table FROM STDIN PARSER public.fcsvparser(type='traditional',header=true,delimiter='|') abort on error no commit;", my_file)

试图实现:

插入vertica_table 从 df 选择 *

或者

合并到 vertica_table 使用 df

如果可以做到,你能帮忙吗?

【问题讨论】:

    标签: python pandas dataframe vertica


    【解决方案1】:

    是的,可以将数据直接从 pandas DataFrame 加载到 Vertica 表中,而无需创建中间 CSV 文件。一种方法是使用 Vertica Python 库 vertica_python,它提供了一个从 Python 连接到 Vertica 并与之交互的接口。

    以下是使用 vertica_python 库将数据从 pandas DataFrame 加载到 Vertica 表中的示例代码 sn-p:

    import vertica_python
    import io
    
    # create a connection to Vertica
    conn_info = {'host': 'your_host', 'port': 5433, 'user': 'your_user', 'password': 'your_password', 'database': 'your_database'}
    connection = vertica_python.connect(**conn_info)
    
    # create a cursor
    cur = connection.cursor()
    
    # convert the DataFrame to a CSV string
    csv_buffer = io.StringIO()
    df.to_csv(csv_buffer, index=False, header=False, sep='|')
    csv_str = csv_buffer.getvalue()
    
    # use the copy() method to load the data directly into the Vertica table
    cur.copy("COPY vertica_table FROM STDIN DELIMITER '|' DIRECT", csv_str)
    
    # commit the transaction
    connection.commit()
    
    # close the cursor and the connection
    cur.close()
    connection.close()
    

    vertica_table 是要加载数据的 Vertica 表的名称,df 是包含要加载的数据的 pandas DataFrame。使用DataFrame的to_csv()方法,将数据转换为CSV字符串,然后使用Vertica游标对象的copy()方法加载到Vertica表中。

    请注意,DIRECT 选项与COPY 命令结合使用,可绕过任何中间文件或表,将数据直接从客户端加载到 Vertica 服务器。

    我希望这是有用的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多