No_body
No_body

Reputation: 842

How to deal with TypeError: must be str, not float

I am trying to run this

 pa['pattern'] = pa['AccessType']  + pa.groupby(['AccessedBy'])['AccessType'].shift(1)

but it's throwing

  TypeError: must be str, not float

But

AccessedBy                 object
AccessType                 object

It was running fine when I last run it few days back. what am I missing ?

Upvotes: 0

Views: 1793

Answers (2)

Joe
Joe

Reputation: 889

Convert one of the column in your DataFrame that you use as parameter to str by typecasting it before you do the groupby().

df['column name'] = df['column name'].astype(str)

Upvotes: 1

Scott Boston
Scott Boston

Reputation: 153460

I think you're data might have changed:

df = pd.DataFrame({'Group':['X']*4+['Z']*4, 'AccessType':[*'ABCDEFGH']})

df['AccessType'] + df.groupby('Group')['AccessType'].shift(1)

Runs fine:

0    NaN
1     BA
2     CB
3     DC
4    NaN
5     FE
6     GF
7     HG
Name: AccessType, dtype: object

However, you have to deal with those NaN.

But, if we change 'A' to a numerical 1:

df = pd.DataFrame({'Group':['X']*4+['Z']*4, 'AccessType':[1]+[*'BCDEFGH']})

df['AccessType'] + df.groupby('Group')['AccessType'].shift(1)

You get:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Upvotes: 1

Related Questions