gpt4 book ai didi

python - Pandas - 行之间的比率

转载 作者:行者123 更新时间:2023-11-30 22:00:55 24 4
gpt4 key购买 nike

我需要找出列中元素相对于该列中的某个值比例。例如,在此表 A 中,我想找出列 Metric 与该列的值 {id1=x and id2=z} 的比率。请问有人可以帮我吗?

例如:

表A

+-------+------+-------+
| id1 | id2 | metric|
+-------+------+-------+
| x | z | 100 |
| x | w | 10 |
+-------+------+-------+

正确结果:

表B

+-------+------+-------+-------+
| id1 | id2 | metric| result|
+-------+------+-------+-------+
| x | z | 100 | 1 | (100/100)
| x | w | 10 | 0.1 | (10/100)
+-------+------+-------+-------+

代码:

d = {'id1': ['x', 'x'], 'id2': ['z','w'], 'metric': [100,10] }
df = pd.DataFrame(data=d)
df

最佳答案

如果我理解正确,您描述的是以下内容:

设置

d = {'id1': ['x', 'x'], 'id2': ['z','w'], 'metric': [100,10] }
df = pd.DataFrame(data=d)
df

解决方案

# Manually choose the value by which to scale the column 'metric'
scaler = df.loc[(df['id1'] == 'x') & (df['id2'] == 'z'), 'metric'].values

# Divide all 'metric' values by the above scaler value
df['result'] = df['metric'] / scaler

df
id1 id2 metric result
0 x z 100 1.0
1 x w 10 0.1

关于python - Pandas - 行之间的比率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198815/

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