简体   繁体   English

将列中的值除以列名的值

[英]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].因此,假设您有一个 DataFrame,它具有列名/值 [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).现在我想将 dataframe 中的每个值除以列的值(列表示数值)。 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.我可以用 for 循环来做,但我宁愿用 lambda function 来做,但我找不到如何用 Z945F3FC449518A73B9F5F146 函数的标准解释来解决它。 The version with the for-loop works, but I'm afraid it won't scale well when the dataframe becomes larger.带有 for 循环的版本可以工作,但是当 dataframe 变大时,恐怕它不会很好地扩展。 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:假设你有这个 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:然后可以用.divide来划分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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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