我正在尝试使用我在某个地方获取的以下代码将行插入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编码文件读取的数据帧中读取的。我尝试了以下操作来清除原始数据帧,但没有成功:
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)

我想知道:
如何从数据帧中删除包含0x00的行:
如果有任何方法可以跳过bulkinser中的坏行;

最佳答案

您应该使用strip('\x00')

b = b'caf\xc3\xa9\x00\x00';
print(b.decode('utf8').strip('\x00'))

replace('\x00', ' ')
b = b'caf\xc3\xa9\x00\x00';
print(b.decode('utf8').replace('\x00', ' '))

输出
café

关于pandas - 从psycopg2游标的pandas数据帧中删除编码“UTF8”:0x00字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56237415/

10-10 09:51
查看更多