pandas Python类型错误:类型为'numpy.int64'的对象没有len()

beq87vna  于 2023-05-05  发布在  Python
关注(0)|答案(3)|浏览(270)

你好,我试图在Python中使用多个唯一行创建Excel。
但是,在执行下面的代码时,我得到了一个TypeError消息(TypeError: object of type 'numpy.int64' has no len())

data = {'ID': ['1', '2', '2', '3'],
        'Name': ['Jack', 'John', 'Steve', 'James']}
with pd.ExcelWriter('output.xlsx') as writer:  
    for name in data['ID'].unique():
        df = data[data['ID'] == name]
        df.to_excel(writer, sheet_name=name)

下面是错误的更多细节

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-aa4fe5c451f7> in <module>
      2     for name in df_sm['model_id_x'].unique():
      3         df = df_sm[df_sm['model_id_x'] == name]
----> 4         df.to_excel(writer, sheet_name=name)
770         # Check that sheet sheetname is <= 31. Excel limit.
--> 771         if len(sheetname) > 31:
    772             raise InvalidWorksheetName(
    773                 "Excel worksheet name '%s' must be <= 31 chars." %

有人可以帮助我如何解决这个问题吗?
先谢谢你了!

owfi6suc

owfi6suc1#

您提供的代码不能重现您的错误(初始代码抛出错误,因为data不是DataFrame;我修改了这个问题)。

data = pd.DataFrame({'ID': ['1', '2', '2', '3'],
                     'Name': ['Jack', 'John', 'Steve', 'James']})

with pd.ExcelWriter('output.xlsx') as writer:
    for name in data['ID'].unique():
        df = data[data['ID'] == name]
        df.to_excel(writer, sheet_name=name)
        # no error raised!

然而,当列ID第一次被强制转换为整数时,它会抛出错误,例如data['ID'] = pd.to_numeric(data['ID'])

File ... , line 807, in _check_sheetname
    if len(sheetname) > 31:

TypeError: object of type 'numpy.int64' has no len()

这显然是因为sheet_name参数被假定为字符串。xlsxwriter/workbook.py处的代码意味着做出此假设是因为Excel文件的工作表长度不能超过31个字符。将ID变量转换为字符串-data['ID'] = data['ID'].astype(str)-并重新执行。

h7wcgrx3

h7wcgrx32#

我运行了你的代码下面的行修改了,它对我工作-

df.to_excel(writer, sheet_name=str(name))

根据数据,创建了3张带ID的图纸。

pgvzfuti

pgvzfuti3#

您的代码需要进行一些更改以重现错误(ID必须是整数)。在使用astype进行处理之前,可以确保ID列是字符串。一个很好的增强是按ID分组,而不是使用自己的掩码。两者都可以工作,但groupby有点紧。

import pandas as pd

data = {'ID': [1, 2, 2, 3],
        'Name': ['Jack', 'John', 'Steve', 'James']}
        
df = pd.DataFrame(data)

df['ID'] = df['ID'].astype(str)

with pd.ExcelWriter('output.xlsx') as writer:  
    for name, group in df.groupby('ID'):
        group.to_excel(writer, sheet_name=name)

相关问题