【问题标题】:Program is returning the following TypeError: Can't convert 'int' object to str implicitly程序返回以下类型错误:无法将“int”对象隐式转换为 str
【发布时间】:2016-12-15 21:38:42
【问题描述】:

我收到上述类型错误:

TypeError: 无法将 'int' 对象隐式转换为 str。

第 34 行,<lambda>

output[column] = output['Index_for_s'].apply(lambda x: s(x, column, file_two))

尝试运行以下程序时:

import pandas as pd

import os


def get_index(x, data):
    return list(data[data['COL1'] == x].index)


def suvrule(ind, col, data):
    data=pd.DataFrame(data)
    return  data.ix [ind,col].sum() 

file_one_path = input('Please enter file one: ')
file_two_path = input('Please enter file two: ')

if os.path.exists(file_one_path) and os.path.exists(file_two_path):
    file_one = pd.read_csv(file_one_path)
    file_two = pd.read_csv(file_two_path)
    try:
        assert (file_one.shape[0] == file_one.shape[0])
    except AssertionError:
        print ("Check Data.")
        exit()

    output = file_one.groupby('COL1', sort='False')['COL2'].agg('count').reset_index()
    output['Index_for_s'] = output['COL1'].apply(lambda x: get_index(x, file_one))
    cols_for_s = [col for col in file_two.columns if 'Header' not in col]
    for column in cols_for_s:
        output[column] = output['Index_for_s'].apply(lambda x: s(x, column, file_two))
    output = output.drop('Index_for_s', axis= 1)
    print ("\nWriting output to output.csv in current working directory.")
    output.to_csv("output.csv",  index='False')
else:
    print ('Incorrect file path')

【问题讨论】:

  • 请提供一个最小的例子。这里不需要一半的代码。 s 是什么?我没有看到它在任何地方定义。
  • s 应该是 suvrule
  • @MiguelA 你知道你可以编辑你的问题,不是吗?如果应该是suvrule,请更改它。
  • 它不允许我编辑,因为我的帖子主要是代码。

标签: python python-3.x pandas


【解决方案1】:

试试这个: 将行更改为此。 [str(Index_for_s)]

【讨论】:

  • 我认为你写 s(x, column, file_two) 的地方你不应该写 suvrule(x,column,file_two) 因为我没有看到 s 在任何地方定义。
  • 那是上传代码时做的,在我正在运行的程序中正确编写和定义。
  • 试图将一个 str 和一个整数连接在一起。默认情况下,Python 不会自动为您转换。尝试 output[""join(str(e) for e in index_for_x)] 如果这不起作用,那么我需要查看更多你的代码
  • 阅读这篇文章,看看你是否可以联系:teamtreehouse.com/community/…
  • 不幸的是,这也不起作用,这是我到目前为止编写的所有代码。我上传它是因为我看不到它有问题的地方。也许问题出在 survrule 函数中,因为它是从那行代码调用的
猜你喜欢
  • 2017-12-21
  • 2017-01-26
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 2017-08-24
  • 1970-01-01
相关资源
最近更新 更多