我有以下df:
df
Process Commodity Direction ratio ratio-min
0 Coal plant Coal In 1.00 NaN
1 Coal plant Elec Out 0.40 NaN
2 Coal plant CO2 Out 0.30 NaN
3 Lignite plant Lignite In 1.00 NaN
4 Lignite plant Elec Out 0.40 NaN
5 Lignite plant CO2 Out 0.40 NaN
6 Gas plant Gas In 1.00 NaN
7 Gas plant Elec Out 0.60 NaN
8 Gas plant CO2 Out 0.20 NaN
9 Biomass plant Biomass In 1.00 NaN
10 Biomass plant Elec Out 0.35 NaN
11 Biomass plant CO2 Out 0.00 NaN
12 Wind park Wind In 1.00 NaN
13 Wind park Elec Out 1.00 NaN
14 Hydro plant Hydro In 1.00 NaN
15 Hydro plant Elec Out 1.00 NaN
16 Photovoltaics Solar In 1.00 NaN
17 Photovoltaics Elec Out 1.00 NaN
正如您所见,ratio
值是浮点数。
我正在尝试使用sqlalchemy将此数据帧发送到数据库。
我在这里设置表格:
import sqlalchemy as sa
table = sa.Table(table_name,
metadata,
sa.Column('index', sa.Integer, primary_key=True, autoincrement=True, nullable=False),
sa.Column('Process', sa.VARCHAR(50)),
sa.Column('Commodity', sa.VARCHAR(50)),
sa.Column('Direction', sa.VARCHAR(50)),
sa.Column('ratio', sa.Float(10)),
sa.Column('ratio-min', sa.Float(10)),
schema=schema_name)
然后我通过以下方式将表格发送到数据库:df.to_sql(table_name, engine, schema=schema_name, if_exists='replace')
问题是,当我检查数据库时,ratio
的所有值都以某种方式舍入。以下是我从数据库获得的内容(在数据库中也是相同的舍入值)
Process Commodity Direction ratio ratio-min
0 Coal plant Coal In 1.0 None
1 Coal plant Elec Out 0.0 None
2 Coal plant CO2 Out 0.0 None
3 Lignite plant Lignite In 1.0 None
4 Lignite plant Elec Out 0.0 None
5 Lignite plant CO2 Out 0.0 None
6 Gas plant Gas In 1.0 None
7 Gas plant Elec Out 1.0 None
8 Gas plant CO2 Out 0.0 None
9 Biomass plant Biomass In 1.0 None
10 Biomass plant Elec Out 0.0 None
11 Biomass plant CO2 Out 0.0 None
12 Wind park Wind In 1.0 None
13 Wind park Elec Out 1.0 None
14 Hydro plant Hydro In 1.0 None
15 Hydro plant Elec Out 1.0 None
16 Photovoltaics Solar In 1.0 None
17 Photovoltaics Elec Out 1.0 None
我怎么能阻止to_sql
围绕我的ratio
值?
您可以通过指定列的数据类型来解决此问题,如下所示:
from sqlalchemy.types import Float
然后加
dtype={'ratio': Float()}
对于df.to_sql
的论点:
df.to_sql(table_name, engine, schema=schema_name, if_exists='replace', dtype={'ratio': Float()})
参数dtype
是一个字典,它将列名作为键,数据类型作为值。这应该可以防止你的ratio
值被舍入。