如何解决TypeError:序列项1:预期的str实例,int发现(Python)?



寻求您的帮助关于这个问题,我试图解决它,尝试了这么多语法,但仍然得到相同的错误。我有多个csv文件要转换,我拉相同的数据,脚本工作为我的csv文件的1,但不是在另一个。期待您的反馈。非常感谢。

我代码:

import os

import pandas as pd

directory = 'C:/path'Ext = ('.csv')

用于os.listdir(目录)中的文件名:F = os.path。加入(目录,文件名)

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:PathMyProject.py", line 34, in <module>
new[merged_col] = new[merge_columns].apply(lambda x:    '.'.join(x), axis=1)
File "C:PathMyProject.py", line 9565, in apply
return op.apply().__finalize__(self, method="apply")
File "C:PathMyProject.py", line 746, in apply
return self.apply_standard()
File "C:PathMyProject.py", line 873, in  apply_standard
results, res_index = self.apply_series_generator()
File "C:PathMyProject.py", line 889, in  apply_series_generator
results[i] = self.f(v)
File "C:PathMyProject.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

如果不显示数据样本,就很难说您想要实现什么。但无论如何,要修复这个错误,您需要在调用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)

相关内容

最新更新