英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论