I have two dataframes where I am converting float values to string as part of a vlookup process. Below are my two dataframe table layouts:
df:
Item Number | Item Description | Item Class | Item Class Description
ABC123 Diamond 0001 Gemstone
ABC456 Sapphire 0001 Gemstone
DEF000 Silicon 0002 Mineral
df2:
Item Class | Item Class Description
0001 Gemstone
0002 Mineral
I was able to get the Item Class values formatted correctly by doing the following (values were imported as float and had some NaNs):
df['Item Class']=df['Item Class'].fillna(value=0,inplace=False)
df['Item Class']=df['Item Class'].astype(int,copy=True,errors='raise')
df['Item Class']=df['Item Class'].astype(str,copy=True,errors='raise')
df['Item Class']=df['Item Class'].apply('{:0>4}'.format)
df2['Item Class']=df2['Item Class'].fillna(value=0,inplace=False)
df2['Item Class']=df2['Item Class'].astype(int,copy=True,errors='raise')
df2['Item Class']=df2['Item Class'].astype(str,copy=True,errors='raise')
df2['Item Class']=df2['Item Class'].apply('{:0>4}'.format)
I tried to create a function to condense this:
def float_to_str(df_column):
df_column=df_column.fillna(value=0,inplace=False)
df_column=df_column.astype(int,copy=True,errors='raise')
df_column=df_column.astype(str,copy=True,errors='raise')
df_column=df_column.apply('{:0>4}'.format)
But when I call the function with
float_to_str(df['Item Class'])
or
float_to_str(df2['Item Class'])
instead of formatting the Item Class values, the values are not converted, and I either get the error message ‘ValueError: You are trying to merge on float64 and object columns. If you wish to proceed you should use pd.concat’, or the df2 values are left as float, indicating in both cases the function didn’t call correctly. How can I have this function call correctly to condense this code?