【问题标题】:Convert numpy.int64 to python int in pandas在熊猫中将 numpy.int64 转换为 python int
【发布时间】:2017-09-21 11:10:19
【问题描述】:

我有一个带有一张纸的 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,但它们根本不起作用。仅当数据帧具有所有整数值时,问题似乎仍然存在。如果您至少有一列类型为字符串或日期,则程序正常工作。我该如何解决这个问题?

【问题讨论】:

标签: python pandas dataframe sqlalchemy


【解决方案1】:

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

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 条记录的数据框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2020-07-28
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多