如何计算一列中的值相对于列最大值的百分比。

huangapple go评论62阅读模式
英文:

How to calculate the percent for values in a column against the column max

问题

Here is the translated code portion:

import pandas as pd
import matplotlib.pyplot as plt

# Create the dataframe from the values in the OP
counts = [40, 40, 40, 40, 40, 33, 17]
df = pd.DataFrame(data=counts, columns=['counts'], index=['A', 'B', 'C', 'D', 'E', 'F', 'G'])

# Add a percent column
df['%'] = df['counts'].div(df['counts'].sum()).mul(100).round(2)

df

This code creates a DataFrame from the provided counts and calculates the percentages in the second column as you described.

英文:

My values are = [40,40,40,40,40,33,17]

I want calculate and add them to second column with percentages, so my outcome should be like this:

first_column=[40,40,40,40,40,33,17]

second_column=[100,100,100,100,100,82.5,42.5]

But I want to python to calculate for me and wrote to the second column...

import pandas as pd

import matplotlib.pyplot as plt

# create the dataframe from values in the OP

counts = [40,40,40,40,40,33,17]

df = pd.DataFrame(data=counts, columns=['counts'], index=['A','B','C','D','E','F','G'])

# add a percent column

df['%'] = df.counts.div(df.counts.sum()).mul(100).round(2)

df

This above thinks as the sum of them as 40+40+40...
but in my case 100% is 40.

答案1

得分: 2

你可以使用以下代码:

df['%'] = 100 / df['counts'].max() * df['counts']
print(df)

# 输出结果
   counts      %
A      40  100.0
B      40  100.0
C      40  100.0
D      40  100.0
E      40  100.0
F      33   82.5
G      17   42.5
英文:

You can use:

df['%'] = 100 / df['counts'].max() * df['counts']
print(df)

# Output
   counts      %
A      40  100.0
B      40  100.0
C      40  100.0
D      40  100.0
E      40  100.0
F      33   82.5
G      17   42.5

huangapple
  • 本文由 发表于 2023年4月17日 19:41:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定