繁体   English   中英

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

[英]Convert numpy.int64 to python int in pandas

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM