python - Pandas - 行之间的比率

标签 python python-3.x pandas pandas-groupby sklearn-pandas

我需要找出列中元素相对于该列中的某个值比例。例如,在此表 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/

相关文章:

Python3 : Iterating a binary string turns character into integer

python-3.x - 使用过去可以通过 pip 安装但现在不能安装的库 (ocrodjvu)?

python - 从 url 检索图像或音频文件

python - ERR_TOO_MANY_REDIRECTS django 2.1 的问题

python - Pandas 的自然排序

python - 每组最近 n 天的计数

python - 比较两个图像(包含建筑物)的相似性的最有效方法是什么

python - 如何在嵌套的 GridSpec 中拥有辅助 y 轴?

python如何将数据框中的一列转换为日期类型和绘图

python - 创建与另一个尺寸相同的空数据框?