通过两列数据框上的group by创建比例

2024-09-02 22:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据集:

df = d = pd.DataFrame({
'duplicates': [
     [('007', "us1", "us2", "time1", 'time2', 4)],
     [('008', "us1", "us2", "time1", 'time2', 5)],
     [('009', "us1", "us2", "time1", 'time2', 6)],
     [('007', 'us2', "us3", "time1", 'time2', 4)],
     [('008', 'us2', "us3", "time1", 'time2', 7)], 
     [('009', 'us2', "us3", "time1", 'time2', 11)], 
     [('001', 'us5', 'us1', "time1", 'time2', 0)], 
     [('008', 'us5', 'us1', "time1", 'time2', 19)], 
     [('007',"us3", "us2", "time1", 'time2', 2)],
     [('007',"us3", "us2", "time1", 'time2', 34)],
     [('009',"us3", "us2", "time1", 'time2', 67)]],
'numberOfInteractions': [1, 2, 3, 4, 5, 6, 7, 8, 1, 1, 11]
   })

我是这样做的:

df['duplicates'] = df.apply(
            lambda x: [(x['numberOfInteractions'],a, b, c, d, e, f) for a, b, c, d, e, f in x.duplicates], 1)


user_record_access =(pd.DataFrame(df["duplicates"].explode().tolist(),
                  columns=["numberOfInteractions", "ID","USER1","USER2","TAU1","TAU2","DELAY"])
     .groupby(["USER1","USER2"])["numberOfInteractions"]
     .agg(sum).to_frame().reset_index())

然后我想得到这样一个数据集:

USER1   USER2   numberOfInteractions    proportion
us1     us2       6                     0.315789
us2     us3       15                    1
us3     us2       13                    0.684211
us5     us1       15                    1.000000

在这种情况下,我想要的“比例”:

- numberOfInteractions of the line/sum(numberOfInteractions of USER2)

例如:

  • 给出第一行,我得到us1us2,然后我得到6/(13+6)。(作为用户2,us2的所有交互数量分别为13和6)

但我不知道如何,我尝试了一些事情(如下面的一个),但没有成功:

user_record_access['proportion'] = user_record_access['numberOfInteractions']/user_record_access['sumUSER2'] #.apply(lambda x: x['numberOfInteractions']/x['numberOfInteractions'].sum(skipna=True)).reset_index()

Tags: dfaccessrecordduplicatessumuseruser1user2
1条回答
网友
1楼 · 发布于 2024-09-02 22:44:38

使用:

# Note: Here 'df1' refers to the dataframe 'user_record_access'
s = df1.groupby('USER2')['numberOfInteractions'].transform('sum')
df1['proportion'] = df1['numberOfInteractions'].div(s)

详细信息:

USER2列上使用^{}并使用^{}使用^{}numberOfInteractions列转换:

print(s)
0    19
1    15
2    19
3    15
Name: USER2, dtype: int64

使用^{}将列numberOfInteractions除以转换后的系列s,并将此结果分配回新列proportions

print(df1)
  USER1 USER2  numberOfInteractions  proportion
0   us1   us2                     6    0.315789
1   us2   us3                    15    1.000000
2   us3   us2                    13    0.684211
3   us5   us1                    15    1.000000

相关问题 更多 >