pymysql insert dataframe 遇到 nan 值

def get_db_conn():
    """MYSQL连接"""
    host = Config.MYSQL["host"]
    pwd = Config.MYSQL["pwd"]
    user = Config.MYSQL["user"]
    port = Config.MYSQL["port"]
    database = Config.MYSQL["database"]
    conn = pymysql.Connect(host=host, port=port, user=user, passwd=pwd, db=database, charset='utf8')
    return conn

def insert_data(df):
    df = df.where(df.notnull(), None)
    conn = get_db_conn()
    cur = conn.cursor()
    sql = f"""INSERT INTO alg_cluster_info({','.join(df.columns)})
    VALUES({','.join(['%s']*len(df.columns))})"""
    print(sql)
    try:
        cur.executemany(sql, [tuple(x) for x in df.values])
        conn.commit()
    except Exception as err:
        conn.rollback()
        log.error("{}".format(err))
    finally:
        cur.close()
        conn.close()

你可能感兴趣的:(python)