首页 > 解决方案 > 获取 TypeError: sequence item 1: expected str instance, Timestamp found 会有什么问题?

问题描述

出现以下错误..

回溯(最后一次调用):文件“C:/BAB/POC/comparesheets.py”,第 54 行,在 sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].apply(lambda x: ''.join(x) , 轴 = 1) 文件“C:\2020\python\lib\site-packages\pandas\core\frame.py”,第 6878 行,在应用中返回 op.get_result() 文件“C:\2020\python\lib \site-packages\pandas\core\apply.py",第 186 行,在 get_result 中返回 self.apply_standard() 文件 "C:\2020\python\lib\site-packages\pandas\core\apply.py",行296,在 apply_standard 值中,self.f,axis=self.axis,dummy=dummy,labels=labels 文件“pandas_libs\reduction.pyx”,第 618 行,在 pandas._libs.reduction.compute_reduction 文件“pandas_libs\reduction.pyx ",第 128 行,在 pandas._libs.reduction.Reducer.get_result 文件 "C:/BAB/POC/comparesheets.py",第 54 行,在 sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].apply(lambda x: ''.join(x), axis = 1) TypeError: sequence item 1: expected str instance, Timestamp found

代码……</p>

sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].apply(lambda x: ''.join(x), axis = 1)

我将如何更改以上行以避免错误?

标签: pythonpandas

解决方案


如果要避免加入所有datetimes列,请添加DataFrame.select_dtypes

sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].select_dtypes(object).apply(lambda x: ''.join(x), axis = 1)

如果还想要列,则通过以下datetimes方式将所有列转换为字符串DataFrame.astype

sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].astype(str).apply(lambda x: ''.join(x), axis = 1)

编辑:

expectedsheetkeycols = ['Date','a','b']
rng = pd.date_range('2017-04-03', periods=5)
sheet1 = pd.DataFrame({'Date': rng, 'a': list('abcde'),'b': list('fghij')})  
print (sheet1)
        Date  a  b
0 2017-04-03  a  f
1 2017-04-04  b  g
2 2017-04-05  c  h
3 2017-04-06  d  i
4 2017-04-07  e  j

sheet1['KEY_COLUMN1']=sheet1[expectedsheetkeycols].select_dtypes(object).apply(lambda x: ''.join(x), axis = 1)
sheet1['KEY_COLUMN2']=sheet1[expectedsheetkeycols].astype(str).apply(lambda x: ''.join(x), axis = 1)
print (sheet1)
        Date  a  b KEY_COLUMN1   KEY_COLUMN2
0 2017-04-03  a  f          af  2017-04-03af
1 2017-04-04  b  g          bg  2017-04-04bg
2 2017-04-05  c  h          ch  2017-04-05ch
3 2017-04-06  d  i          di  2017-04-06di
4 2017-04-07  e  j          ej  2017-04-07ej

推荐阅读