python - 在 Pandas 中将 numpy.int64 转换为 python int

标签 python pandas dataframe sqlalchemy

我有一个只有一张纸的 excel 文件。这包含两列 num1、num2,它们都有整数值。我正在尝试使用 Sqlalchemy 和 pandas 提取这些数据并将其插入到 Mysql 数据库中。

from sqlalchemy import create_engine, MetaData,Column,Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,validates
import pandas as pd

Base = declarative_base()
connection_string = # give your connection string here
engine= create_engine(connection_string)
Base.metadata.bind = engine
s = sessionmaker()
session = s()

class a(Base):
    __tablename__ = 'a'
    id = Column(Integer,primary_key=True)
    num1 = Column(Integer)
    num2 = Column(Integer)

a.__table__.create(checkfirst=True)

excel_sheet_path = # give path to the excel sheet
sheetname = # give your sheet name here

df = pd.read_excel(excel_sheet_path,sheetname).transpose()


dict = df.to_dict()

for i in dict.values():
    session.add(a(**i))
session.commit()

这段代码向我抛出一个 AttributeError

AttributeError: 'numpy.int64' object has no attribute 'translate'

因此,在将数据帧转换为字典之前,我尝试了很多函数,如 astype、to_numeric 以将数据类型更改为普通的 python int,但它们根本不起作用。只有当数据帧具有所有整数值时,问题似乎才会持续存在。如果您至少有一个字符串或日期类型的另一列,那么该程序将正常运行。我该如何解决这个问题?

最佳答案

这个也有问题。 我终于找到了一个有点不熟练的解决方案如下:

def trans(data):
"""
translate numpy.int/float into python native data type
"""
result = []
for i in data.index:
    # i = data.index[0]
    d0 = data.iloc[i].values
    d = []
    for j in d0:
        if 'int' in str(type(j)):
            res = j.item() if 'item' in dir(j) else j
        elif 'float' in str(type(j)):
            res = j.item() if 'item' in dir(j) else j
        else:
            res = j
        d.append(res)
    d = tuple(d)
    result.append(d)
result = tuple(result)
return result

但是,它在处理具有大量行的数据时表现不佳。您将花几分钟时间翻译一个包含超过 100,000 条记录的数据框。

关于python - 在 Pandas 中将 numpy.int64 转换为 python int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342405/

相关文章:

python - 使用 python 拆分系列中的每个元素

python - CSRF token 丢失或不正确,即使我有 {% csrf_token %} 但我使用 HttpResponse

python - 对于数据框中的每一列和单元格,使用该列中的随机值填充 NaN/Nulls

python - 计算不同长度向量中元素出现的总数

r - 请遗漏数据

python - 从 pandas 数据框中选择具有相同数据的行

python - 带有对象的 MVC 游戏设计

Python - 查找同时在 string1 和 string2 中找到的字符数

python - 在没有已知函数的情况下将数据拟合到曲线