【问题标题】:Count combinations of values using pandas crosstab使用 pandas 交叉表计算值的组合
【发布时间】:2022-07-08 16:46:49
【问题描述】:

我想计算每组 (user) 的值组合 (pets)。下面的代码给出了想要的结果。但是,我正在寻找一种更“流行”的方式,也许是使用crosstab 方法。对于不那么冗长的解决方案有什么建议吗?

import pandas as pd
import numpy as np
import itertools
df1 = pd.DataFrame({'user':['Jane', 'Matthew', 'Emily'], 'pets':[['dog', 'cat', 'lizard'], ['dog', 'spider'], ['dog', 'cat', 'monkey']]}).explode('pets')
combinations = []
for g in df1.groupby('user'): combinations += [x for x in itertools.combinations(g[1].pets, 2)]
df2 = pd.DataFrame(np.zeros((df1.pets.nunique(), df1.pets.nunique()), dtype=int), columns=df1.pets.unique(), index=df1.pets.unique())
for x in combinations:
    df2.at[x[0], x[1]] += 1
    df2.at[x[1], x[0]] += 1
print(df2)

结果:

        dog  cat  lizard  spider  monkey
dog       0    2       1       1       1
cat       2    0       1       0       1
lizard    1    1       0       0       0
spider    1    0       0       0       0
monkey    1    1       0       0       0

【问题讨论】:

    标签: python pandas dataframe crosstab


    【解决方案1】:

    用途:

    df = df.merge(df, on='user')
    df = pd.crosstab(df.pets_x, df.pets_y)
    print (df)
    
    pets_y  cat  dog  lizard  monkey  spider
    pets_x                                  
    cat       2    2       1       1       0
    dog       2    3       1       1       1
    lizard    1    1       1       0       0
    monkey    1    1       0       1       0
    spider    0    1       0       0       1
    

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多