简体   繁体   中英

Divide values in a column by the value of the column name

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM