Pandas - 行间比率

Pandas - Ratio between rows

我需要找出某列元素相对于该列某个值比例。例如,在此 Table A 中,我想找出列 Metric 与 {id1=x 和 id2=z[= 的值的比率本栏的 32=]}。有谁能帮帮我吗?

例如:

Table一个

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

正确结果:

Table 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