gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:40:27 25 4
gpt4 key购买 nike

我正在尝试使用我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com