问题描述
我尝试将pandas DataFrame中的数据插入PostgreSQL表中,
I try to insert data from pandas DataFrame into the PostgreSQL table,
表如下:
city_id date forecast
5 29.05.2019 0
1 29.05.2019 0
151 29.05.2019 0
55 29.05.2019 0
...
类型:
-
city_id
-numpy.int64
-
date
-datetime.date
-
forecast
-numpy.int64
city_id
-numpy.int64
date
-datetime.date
forecast
-numpy.int64
以及将数据插入db的代码块:
And the block of code, that inserting data to db:
with psycopg2.connect(f"host='{hostname}' \
dbname='{database}' \
user='{username}' \
password='{password}'") as connection:
with connection.cursor() as cursor:
connection.set_client_encoding('UTF8')
for i in df_with_new_one.index:
date = df_with_new_one['date'][i]
city_id = df_with_new_one['city_id'][i]
value = df_with_new_one['forecast'][i]
cursor.execute("INSERT INTO forecast \
(city_id, computed_time, date, value) \
VALUES (%s, %s, %s, %s)", (city_id, now, date, value))
其中now
被保存为datetime.datetime.now()
然后我得到 ProgrammingError :
ProgrammingError: can't adapt type 'numpy.int64'
我检查了类型 type(df_with_new_one['forecast'][0])
类型是numpy.int64
所以我发现PostreSQL只能读取pythonic int
和float
,而我尝试的第一件事是使用以下命令将np.int64
转换为简单的int
:
So I get that PostreSQL can read only pythonic int
and float
, and the first thing i've tried was converting np.int64
into simple int
with:
-
tolist()
-
pd.to_numeric()
-
int()
为((int(city_id), now, date, int(value))
-
.astype(int)
-
.value.astype('int')
tolist()
pd.to_numeric()
int()
for((int(city_id), now, date, int(value))
.astype(int)
.value.astype('int')
更新.
-
city_id = int(df_with_new_one['city_id'][i])
value = int(df_with_new_one['forecast'][i])
不幸的是,它们都不对我有用
当我尝试int()
时,出现另一个错误:
When I tried int()
I get another error:
TypeError: cannot convert the series to <class 'int'>
我发现的答案,但没有人帮助我
- psycopg2:无法采用类型'numpy.int64'
- ProgrammingError:(psycopg2.ProgrammingError)无法适应类型' numpy.ndarray'
- Python TypeError:无法将系列转换为< class'int'>尝试在数据框上进行数学运算时
- Python熊猫过滤; TypeError:无法将系列转换为< class'int'>
- psycopg2: can't adapt type 'numpy.int64'
- ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'numpy.ndarray'
- Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe
- Python Pandas filtering; TypeError: cannot convert the series to <class 'int'>
是否有任何其他方法来更改值的类型?
Are there any other methods to change type of values?
推荐答案
问题出在错误的索引编制中:
The problem was in wrong indexation:
- 第一个索引是从83到1161,在1161之后应该是1161,之后又是83,下一个值是83 + 1,等等.
因此,问题已由.reset_index()
df_with_new_one.reset_index(drop = True, inplace = True)
谢谢大家的回答!
这篇关于如何将np.int64转换为PandasSeries的python int64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!