我有以下数据集:
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)
例如:
但我不知道如何,我尝试了一些事情(如下面的一个),但没有成功:
user_record_access['proportion'] = user_record_access['numberOfInteractions']/user_record_access['sumUSER2'] #.apply(lambda x: x['numberOfInteractions']/x['numberOfInteractions'].sum(skipna=True)).reset_index()
使用:
详细信息:
在} 并使用^{} 使用^{} 从
USER2
列上使用^{numberOfInteractions
列转换:使用^{} 将列
numberOfInteractions
除以转换后的系列s
,并将此结果分配回新列proportions
相关问题 更多 >
编程相关推荐