gpt4 book ai didi

python - 返回列中选择值的百分比计数

转载 作者:行者123 更新时间:2023-12-04 10:46:15 25 4
gpt4 key购买 nike

我有当前的代码,然后是一个如下系列的打印输出

shapes = ['triangle','circle','square']
max_shape = None
max_percent = None
for shape in shapes:
df_overall = df[(df['Shape']== shape)]
num_overall = df_overall.shape[0]
shape_df = df
num_total = shape_df.shape[0]
percentage_overall = num_overall / num_total


if max_shape is None:



print(shape, percentage_overall)

它给了我形状列中每个值的百分比作为一个系列,
triangle 0.672
circle 0.16
square 0.168

我可以代替打印到系列,而是将输出检索为数据帧吗?

最佳答案

放弃循环,您可以通过 value_counts 将其矢量化:

df = pd.DataFrame({'Shape': ['triangle'] * 3 + ['square'] * 2 + ['trapezoid'] * 5})
shapes = ['triangle', 'square']
df.loc[df['Shape'].isin(shapes), 'Shape'].value_counts().div(len(df)).to_frame() 

Shape
triangle 0.3
square 0.2

“我可以将其输出为帧而不是系列吗”是通过调用 to_frame() 解决的一个微不足道的问题。结果上。

关于python - 返回列中选择值的百分比计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com