【发布时间】: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