Reputation: 31
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())
Upvotes: 0
Views: 133
Reputation: 195428
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
Upvotes: 2