pandas - 具有多个值的groupby列

时间:2018-03-12 07:35:32

标签: python pandas

我想显示使用过值的用户。

import pandas as pd
user = ['alice', 'bob', 'tim', 'alice']
val = [['a','b','c'],['a'],['c','d'],['a','d']]
df = pd.DataFrame({'user': user, 'val': val})

user    val
'alice'      [a, b, c]
'bob'        [a]
'tim'        [c, d]
'alice'      [a, d]

期望的输出:

val     users
a      [alice,bob]
b      [alice]
c      [alice,tim]
d      [alice,tim]

有什么想法吗?

4 个答案:

答案 0 :(得分:4)

第1步
重塑您的数据 -

'strict' => false,

第2步
使用from itertools import chain df = pd.DataFrame({ 'val' : list(chain.from_iterable(df.val.tolist())), 'user' : df.user.repeat(df.val.str.len()) }) + groupby + apply

unique

df.groupby('val').user.apply(lambda x: x.unique().tolist())

答案 1 :(得分:1)

这是我的方法。

df2 = (df
       .set_index('user')
       .val
       .apply(pd.Series)
       .stack()
       .reset_index(name='val')  # Reshape the data
       .groupby(['val'])
       .user
       .apply(lambda x: sorted(set(x))))  # Show users that use the value

输出:

print(df2)
# val
# a    [alice, bob]
# b         [alice]
# c    [alice, tim]
# d    [alice, tim]
# Name: user, dtype: object

答案 2 :(得分:1)

我认为需要:

df2 = (pd.DataFrame(df['val'].values.tolist(), index=df['user'].values)
         .stack()
         .reset_index(name='val')
         .groupby('val')['level_0']
         .unique()
         .reset_index()
         .rename(columns={'level_0':'user'})
     )
print(df2)
  val          user
0   a  [alice, bob]
1   b       [alice]
2   c  [alice, tim]
3   d  [tim, alice]

答案 3 :(得分:0)

没有足够的声誉将其写为评论,但这个问题有答案: How to print dataframe without index

基本上,将最后一行改为:

print(df2.to_string(index=False))