python - Pandas to_sql 设置列类型

标签 python pandas postgresql sqlalchemy

我有一个字符串格式的数字列,我想将它作为 float 发送到 PostresSQL。如何确保 SQLAlchemy 将此列设置为 float ? (请注意,列中可能是 NaN)。这是代码

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine('postgresql://{}:{}@{}:5432/{}'.format(USER, DB_PW, HOST, DB))

df = pd.DataFrame({'String2Number': ['0,2', '', '0,0000001']})

df.to_sql(name='TABLE_NAME', con=engine, index=False)

最佳答案

首先,您的数字应该是小数点格式,因此我们需要用逗号替换您的小数点。 接下来你应该确保 to_sql 函数将使用 float,你可以使用 dtype 参数来实现这一点,该参数允许在插入时设置列类型(基于 sqlalchemy types )数据库。这里的代码:

import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import Float # note this import to use sqlalchemy Float type

engine = create_engine('postgresql://{}:{}@{}:5432/{}'.format(USER, DB_PW, HOST, DB))

df = pd.DataFrame({'String2Number': ['0,2', '', '0,0000001']})

# Replacing ',' to '.'
df['String2Number'] = df['String2Number'].apply(lambda x: str(x).replace(',', '.'))

# Set column type as SQLAlchemy Float
df.to_sql(
  name='TABLE_NAME',
  con=engine,
  index=False,
  dtype={'String2Number': Float()}
)

关于python - Pandas to_sql 设置列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57500209/

相关文章:

python - 使机器人对最后一条消息使用react或对带有消息 ID 的消息作出 react

python - Pandas Group By - 按时间和条件分隔

python - 使用 InterX 函数转换为 python 时出现模块错误

postgresql - 哪些订单同时包含产品 2 和 16?我尝试了几种方法来解决这个问题,但它不起作用。在 psql 中

python - 无法将 fdopen 与 mkstemp 一起使用

python pandas column dtype = object 导致合并失败 : DtypeWarning: Columns have mixed types

python - 如何显示存储在 Pandas 数据框中的图像?

sql - 创建自定义事件时间表。我应该使用 "LIKE"吗?

java - Spring JPA 无法将参数传递到引号中

python - 在 python 中使用 map.pool 有什么问题?