0

I have a function called unit_unify() that I want to apply to every column of the dataframe. I have been trying to devise the pandas equivalent using apply/apply map, but have not been successul.

Here is the for loop

for i in df.columns:
    df[i] = unit_unify(df[i], unit_dict)

Here is the attempt at the pandas equivalent of the for loop

df = df.apply(lambda col: unit_unify(df[col], unit_dict))
kapsha
  • 35
  • 4
  • 3
    [`df.apply(unit_unify, args=(unit_dict, ))`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html) – Ch3steR Apr 30 '22 at 03:30
  • 1
    What exactly does your function do? There may be a more efficient way of implementing it~ – BeRT2me Apr 30 '22 at 03:40
  • @BeRT2me it takes in strings like "4 shots" and converts them into ounces using a unit conversion dictionary and another nested function that converts fractions into decimals. – kapsha Apr 30 '22 at 15:39
  • So, the function is designed to be run on every single cell individually, the column/row that it's in doesn't matter, and the `unit_dict` is the same for every cell? – BeRT2me Apr 30 '22 at 21:13

1 Answers1

0

You may check the performance for the for loop and apply:link

[df[i] = unit_unify(df[i], unit_dict) for i in df.columns] 
BENY
  • 317,841
  • 20
  • 164
  • 234