python - 获取 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)
我将如何更改以上行以避免错误?
解决方案
如果要避免加入所有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
推荐阅读
- c - 从 C 中的套接字接收阿拉伯字符
- xml - 使用 beautifulsoup 从 xml 中获取具有不同内容的相同标签
- flutter - 发生异常类“UserSite”没有实例方法“[]”
- python - 使用 add_edge_list() 方法创建图形的最佳方法是什么?
- amazon-web-services - AWS 中国地区是否支持 Bitbucket Pipeline?
- node.js - NodeJS 如何使用 crypto-js 或使用自定义密钥大小、iv、模式和填充以 UTF8 编码的加密包加密(AES 算法)数据
- javascript - 为什么我打开网页时没有图像?
- javascript - 在 Javascript 中,如何使用 fetch() 从一个 API 请求中读取多个流块?
- angular - Angular code splitting into multiple functional bundles
- reactjs - 我如何在循环中实现多个承诺