1

So let's say you have a DataFrame, which has column names/values [1,2,3,4]. Now I want to divide every value in the dataframe by the value of the column (the columns represent numerical values). I could do it with a for loop, but I'd rather do it with a lambda function but I could not find how and could not figure it out with the standard explanations of the working of lambda functions. The version with the for-loop works, but I'm afraid it won't scale well when the dataframe becomes larger. This is what I already have:

values = df.columns #or predefined array, does not really matter in this case
for i in range(len(values)):
    df[values[i]] = df[values[i]] / values[i]
print(df.head())
imRobert7
  • 41
  • 6
  • Don't use a lambda function; use the PANDAS vectorized facilities, those whole-column operations. Any PANDAS tutorial introduces these. If you get stuck, *then* post a question with the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). Please [include a minimal data frame](https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard). – Prune Apr 30 '21 at 20:06

1 Answers1

2

Suppose you have this dataframe:

   10  20  30
0   1   1   1
1   2   2   2
2   3   3   3

Then you can use .divide to divide the dataframe:

print(df.divide(df.columns.astype(float)))

Prints:

    10    20        30
0  0.1  0.05  0.033333
1  0.2  0.10  0.066667
2  0.3  0.15  0.100000
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91