1
votes

Getting following error..

Traceback (most recent call last): File "C:/BAB/POC/comparesheets.py", line 54, in sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].apply(lambda x: ''.join(x), axis = 1) File "C:\2020\python\lib\site-packages\pandas\core\frame.py", line 6878, in apply return op.get_result() File "C:\2020\python\lib\site-packages\pandas\core\apply.py", line 186, in get_result return self.apply_standard() File "C:\2020\python\lib\site-packages\pandas\core\apply.py", line 296, in apply_standard values, self.f, axis=self.axis, dummy=dummy, labels=labels File "pandas_libs\reduction.pyx", line 618, in pandas._libs.reduction.compute_reduction File "pandas_libs\reduction.pyx", line 128, in pandas._libs.reduction.Reducer.get_result File "C:/BAB/POC/comparesheets.py", line 54, in sheet1['KEY_COLUMN']=sheet1[expectedsheetkeycols].apply(lambda x: ''.join(x), axis = 1) TypeError: sequence item 1: expected str instance, Timestamp found

Code …

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

how would I change above line to avoid the error?

1

1 Answers

0
votes

If want avoid join all datetimes columns add DataFrame.select_dtypes:

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

If want also datetimes columns convert all columns to strings by DataFrame.astype:

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

EDIT:

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