pandas - 删除编码 "UTF8": 0x00 chars from pandas dataframe for psycopg2 cursor

标签 pandas postgresql encoding utf-8 sqlalchemy

我正在尝试使用我在 SO 某处获取的以下代码将行插入到 Postgresq 数据库中:

def to_sql(engine, df, table, if_exists='fail', sep='\t', encoding='utf8',
    schema='public', dtypes_sql=None, verbose=False):
    # Create Table
    ## istruzioni diverse se le colonne hanno dtypes diversi
    if verbose==True:
        print("Scrivo tabella targhe su tabella di schema {}".format(schema))
    if dtypes_sql is None:
        df[:0].to_sql(table, engine, if_exists=if_exists,schema=schema, index=False)
    else:
        df[:0].to_sql(table, engine, if_exists=if_exists,schema=schema, index=False,dtype=dtypes_sql)
    # Prepare data
    output = StringIO()
    df.to_csv(output, sep=sep, header=False, encoding=encoding, index=False)
    output.seek(0)

    # Insert data
    connection = engine.raw_connection()
    cursor = connection.cursor()
    #handling different schemas:
    if schema in ['public','dbo']:
        cursor.copy_from(output, table, sep=sep, null='')

    else:
        new_table = schema + "." + table
        cursor.copy_from(output, new_table, sep=sep, null='')
    connection.commit()
    cursor.close()
    if verbose==True:
        print("Saved")
    return None

数据是从最初从 latin1 编码文件中读取的数据帧中读取的。我尝试了以下方法来清理我原来的 DataFrame 但没有成功:

input_file_df.replace(to_replace=b'\x00',value=' ', inplace=True,regex=True)
input_file_df.replace(to_replace="\x00", value=" ",inplace=True)
input_file_df.where(pd.notnull(input_file_df), None,inplace=True)

我想知道:

  1. 如何从 DataFrame 中删除包含 0x00 的行:
  2. 是否有任何方法可以跳过 bulkinser 中的坏行;

最佳答案

删除 pandas 数据框中的 null 可以按如下方式执行:

import re
re_null = re.compile(pattern='\x00')
input_file_df.replace(regex=re_null,value=' ', inplace=True)

这将避免 0x00 问题

关于pandas - 删除编码 "UTF8": 0x00 chars from pandas dataframe for psycopg2 cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237415/

相关文章:

python - 按轴 0 中的单列组合 pandas DataFrame

python - 比较两个不同数据框 pandas 的列

postgresql 插入 bytea 字段

如果我打开 xml 文件,Emacs 会显示中文字符

c# - 如何让 C# 抛出解码异常?

pandas - 如何在数据框(广播)中添加多个列?

html - Postgresql——清理字符串中间的 HTML 标签

ruby-on-rails - Heroku 上的应用程序出现奇怪的日志错误

c# - 使用正确的编码导出文件

python - 如何更改从字典创建的数据帧的索引和列而不显示 NAN 值?