【问题标题】:how many users have the same occurrences of strings value in python [closed]有多少用户在python中具有相同的字符串值[关闭]
【发布时间】:2019-12-13 18:54:56
【问题描述】:

我想知道有多少用户有相同的字符串值 数据为python数据框类型,值的顺序无关紧要,只计算一次(x-y与y-x相同)

user_id    value
1            x
1            y   
2            x
2            y
2            z   
3            x
3            z

Combination   #of user
x-y             2
x-z             2
y-z             1

【问题讨论】:

  • 请发布您已经尝试过的内容以及发现的错误,以便人们可以帮助您。
  • 你可能应该改写这个问题并使其更具可读性 - 这是非常难以理解的

标签: python pandas


【解决方案1】:

为每个组创建组合,然后按chain.from_iterable 展平值并按Counter 计数:

from  itertools import combinations, chain
from collections import Counter

s = df.groupby('user_id')['value'].apply(lambda x: list(map( '-'.join, combinations(x, 2))))
#if necessary sorted combinations
#s = (df.groupby('user_id')['value']
#       .apply(lambda x: ['-'.join(sorted(y)) for y in combinations(x, 2)]))

d = Counter(chain.from_iterable(s))

df = pd.DataFrame({'Combination': list(d.keys()),
                   'user':list(d.values())})
print (df)
  Combination  user
0         x-y     2
1         x-z     2
2         y-z     1

【讨论】:

  • 太棒了!谢谢!
猜你喜欢
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多