处理Pandas DataFrame浮点转整数及NaN值,解决Postgres插入报错
解决方案
方案1:手动处理数据类型后生成插入值
问题出在to_records()会将Pandas的可空整数类型(Int64)转换为Numpy的浮点数组,导致最终传递给Postgres的仍是float和nan,而Postgres的BIGINT无法识别浮点类型的输入。可以手动遍历数据,将浮点值转为整数,nan转为Python原生的None(对应Postgres的NULL):
import pandas as pd # 先确保列是可空整数类型(如果之前没做的话) df["related_player_id"] = df["related_player_id"].astype('Int64') # 手动处理每行数据,生成符合要求的插入值 values = [] for row in df.itertuples(index=False): processed = [] for val in row: if pd.isna(val): processed.append(None) else: processed.append(int(val) if isinstance(val, float) else val) values.append(tuple(processed)) # 之后用execute_values插入即可
方案2:直接使用Pandas的to_sql方法(更简便)
避免手动处理数据格式,让Pandas和SQLAlchemy自动处理类型映射:
from sqlalchemy import create_engine, BigInteger # 创建数据库连接 engine = create_engine("postgresql://<用户名>:<密码>@<主机>:<端口>/<数据库名>") # 插入数据,指定related_player_id的类型为BigInteger df.to_sql( name="player_match_event", con=engine, if_exists="append", index=False, dtype={"related_player_id": BigInteger()} )
这个方法会自动将Pandas的Int64类型映射到Postgres的BIGINT,并将<NA>转换为NULL,无需手动处理数值类型转换。
为什么之前的尝试无效?
Pandas的Int64是扩展可空类型,但to_records()依赖Numpy的原生数据类型,而Numpy没有原生的可空整数类型,所以会将Int64列降级为float64数组,导致最终的values里仍是浮点值和nan,Postgres无法将浮点值直接插入BIGINT列,从而触发"bigint out of range"错误。
内容的提问来源于stack exchange,提问作者raffoth
相关产品推荐
相关产品推荐

