首页 > 解决方案 > 我不知道为什么我在这里得到“只能将 str(而不是“int”)连接到 str”错误

问题描述

代码:

import pandas as pd
app = pd.read_excel("/Users/michaelblack/Downloads/Applicants with Interest/Applicants with Interests 2020.xlsx")
app = app.replace(',',' ', regex=True).replace('/','', regex=True).replace('-','',regex=True).replace(';',' ',regex=True)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
app.fillna(' ', inplace = True)
app.info()
ct = 0
while ct <= 9:
    if ct == 0:
        app['new'+str(ct)] = app['Interest Description'] + ' ' + app['Interest Role']
    else:
        app['new'+str(ct)] = app['Interest Description' + '.' + str(ct)] + ' '+ app['Interest Role' + '.' + str(ct)]
    ct += 1

app.head(5)

我的错误在第 12 行(ct += 1 正上方),它是“只能将 str(而不是“int”)连接到 str”。

对于上下文:我的 Excel 文件中的每个字段都是一个“对象”数据类型,我还有另外两个 Excel 文件,它们的列数、列标题和数据类型完全相同,但值不同,它们都可以工作。

有人可以在这里提供一些指导吗?为了我的一生,我迷失了。当代码完全相同时,我无法理解为什么一个相同的 Excel 文件可以工作,而另一个却不能。

标签: python-3.xpandas

解决方案


尝试将 .astype(str) 添加到每一列:

while ct <= 9:
    if ct == 0:
        app['new'+str(ct)] = app['Interest Description'].astype(str) +' '+ app['Interest Role'].astype(str)
    else:
        app['new'+str(ct)] = app['Interest Description' + '.' + str(ct)].astype(str) + ' '+ app['Interest Role' + '.' + str(ct)].astype(str)
    ct += 1

推荐阅读