如何解决类型错误:序列项1:应为str示例,找到int(Python)?

kmbjn2e3  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(128)

寻求您的帮助有关这个问题,我正试图解决它,尝试了这么多的语法,但仍然得到相同的错误。我得到了多个csv文件要转换,我拉相同的数据,脚本的作品之一,我的csv文件,但不对其他。期待您的反馈。非常感谢。
我的代码:

import os

进口Pandas当PD
目录='C:/路径'扩展名=('. csv ')
对于os. listdir(目录)中的文件名:f = os. path. join(目录,文件名)

if f.endswith(ext):

    head_tail = os.path.split(f)
    head_tail1 = 'C:/path'
    k =head_tail[1]
    r=k.split(".")[0]

    p=head_tail1 + "/" + r + " - Revised.csv"
    mydata = pd.read_csv(f)

    # to pull columns and values
    new = mydata[["A","Room","C","D"]]
    new = new.rename(columns={'D': 'Qty. of Parts'})
    new['Qty. of Parts'] = 1
    new.to_csv(p ,index=False)

    #to merge columns and values
    merge_columns = ['A', 'Room', 'C']
    merged_col = ''.join(merge_columns).replace('ARoomC', 'F')

    new[merged_col] = new[merge_columns].apply(lambda x: '.'.join(x), axis=1)
    new.drop(merge_columns, axis=1, inplace=True)
    new = new.groupby(merged_col).count().reset_index()
    new.to_csv(p, index=False)

我得到的错误:

Traceback (most recent call last):
File "C:Path\MyProject.py", line 34, in <module>
new[merged_col] = new[merge_columns].apply(lambda x:    '.'.join(x), axis=1)
File "C:Path\MyProject.py", line 9565, in apply
return op.apply().__finalize__(self, method="apply")
File "C:Path\MyProject.py", line 746, in apply
return self.apply_standard()
File "C:Path\MyProject.py", line 873, in  apply_standard
results, res_index = self.apply_series_generator()
File "C:Path\MyProject.py", line 889, in  apply_series_generator
results[i] = self.f(v)
File "C:Path\MyProject.py", line 34, in <lambda>
new[merged_col] = new[merge_columns].apply(lambda x: '.'.join(x), axis=1)
TypeError: sequence item 1: expected str instance,  int found
sr4lhrrt

sr4lhrrt1#

如果不展示数据样本,很难说你想达到什么目的,但无论如何,要修复这个错误,你需要在调用pandas.Series.apply时用str将值转换为字符串:

new[merged_col] = new[merge_columns].apply(lambda x: '.'.join(str(x)), axis=1)

或者,您也可以使用pandas.Series.astype

new[merged_col] = new[merge_columns].astype(str).apply(lambda x: '.'.join(x), axis=1)

相关问题