Data_ing
Data_ing

Reputation: 107

Pandas - TypeError: unsupported operand type(s) for +: 'float' and 'str'

I have a function : generateID but I have a problem with this line :

data_df['id_cont'] = data_df.apply(lambda row:row['product_name']+'-'+row['hour_shift'].strftime('%Y-%m-%d %H:%M:%S'),axis=1)

Because of this data conversion problem I have this error :

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

Here is my code :

 def generateID(self,outputMode,data_df):
    
    data_df = self._preGenerateID(outputMode,data_df)
    
    if outputMode.getModeCB() == CONST_MODE_CONT:
        data_df['id_cont'] = data_df.apply(lambda row:row['equipement']+'-'+row['product_name']+'-'+row['hour_shift'].strftime('%Y-%m-%d %H:%M:%S'),axis=1)
   
    else:
        data_df['first_date'] = data_df.groupby(['equipement'])['local_time'].transform('min')
        data_df['year'] = pd.DatetimeIndex(data_df['first_date']).year
        data_df['year'] = data_df['year'].astype(str)

        data_df['id_batch'] = data_df.apply(lambda row:row['equipement']+'-'+row['product_name']+'-'+row['year'],axis=1)
 
    return data_df

Upvotes: 0

Views: 2413

Answers (1)

weasel
weasel

Reputation: 574

One of your columns is a float, and I assume you want to concatenate them as str for strftime. You can try f-strings, or convert your column to str before concatenating.

f-string example:

data_df['id_cont'] = pd.to_datetime(df.apply(
          lambda row:f"{row['equipement']}-{row['product_name']}-{row['hour_shift']}",axis=1)) 

Upvotes: 1

Related Questions