简体   繁体   English

Python:对于每个唯一的ID,找到它的代码和它的值并计算比率

[英]Python: For each unique ID, find its code and its value and calculate the ratio

Actual dataframe consist of more than a million rows.实际数据帧包含超过一百万行。

Say for example a dataframe is:例如说一个数据框是:

UniqueID  Code  Value  OtherData      
1         A     5      Z01 
1         B     6      Z02
1         C     7      Z03
2         A     10     Z11
2         B     11     Z24
2         C     12     Z23 
3         A     10     Z21
4         B     8      Z10

I want to obtain ratio of A/B for each UniqueID and put it in a new dataframe.我想获得每个 UniqueID 的 A/B 比率并将其放入新的数据框中。 For example, for UniqueID 1, its ratio of A/B = 5/6.例如,对于 UniqueID 1,其 A/B 的比率 = 5/6。

What is the most efficient way to do this in Python?在 Python 中执行此操作的最有效方法是什么?

Want:想:

UniqueID  RatioAB        
1         5/6
2         10/11
3         Inf
4         0

Thank you.谢谢你。

One approach is using pivot_table , aggregating with the sum in the case there are multiple occurrences of the same letters (otherwise a simple pivot will do), and evaluating on columns A and B :一种方法是使用pivot_table ,在多次出现相同字母的情况下与sum聚合(否则一个简单的枢轴就可以了),并在AB列上进行评估:

df.pivot_table(index='UniqueID', columns='Code', values='Value', aggfunc='sum').eval('A/B')

    UniqueID
1    0.833333
2    0.909091
3         NaN
4         NaN
dtype: float64

If there is maximum one occurrence of each letter per group:如果每组每个字母最多出现一次:

df.pivot(index='UniqueID', columns='Code', values='Value').eval('A/B')

    UniqueID
1    0.833333
2    0.909091
3         NaN
4         NaN
dtype: float64

If you only care about A/B ratio:如果您只关心 A/B 比率:

df1 = df[df['Code'].isin(['A','B'])][['UniqueID', 'Code', 'Value']]
df1 = df1.pivot(index='UniqueID',
                columns='Code', 
                values='Value')

df1['RatioAB'] = df1['A']/df1['B']

最明显的方式是通过 groupby。

df.groupby('UniqueID').apply(lambda g: g.query("Code == 'A'")['Value'].iloc[0] / g.query("Code == 'B'")['Value'].iloc[0]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM