如何根据python中其他列的条件计算值?

时间:2021-02-18 22:24:43

标签: python pandas

我有一张如下所示的表格:

  Celebrity  Usernames
0         A          2
1         A          1
2         B          3
3         C          2
4         D          2
5         A          3

我想知道有多少用户同时关注了 A、C、D。所以,输出应该是 1。我如何使用 python 来做到这一点?

2 个答案:

答案 0 :(得分:1)

这是使用 groupby()nunique() 的一种方法:

l = ['A','C','D']
df.loc[df['Celebrity'].isin(l)].groupby('Usernames')['Celebrity'].nunique().eq(len(l))

这是另一种方式:

df.groupby(['Usernames','Celebrity']).size().loc[(slice(None),l)].unstack().gt(0)

以及交叉表的替代方案:

df['Celebrity'].str.get_dummies().groupby(df['Usernames']).sum().loc[:,l].astype(bool).all(axis=1)

使用地图:

df.loc[df['Usernames'].map(df.groupby('Usernames')['Celebrity'].agg(set).ge(set(l)))]

答案 1 :(得分:0)

进行交叉表,然后子集到您的列,并利用 bool(0) == Falsebool(any_other_number) == True 的事实来查看有多少用户名满足您的条件。

(pd.crosstab(df['Usernames'], df['Celebrity'])
   .loc[:, ['A', 'C', 'D']]
   .astype(bool)
   .all(axis=1)
   .sum())
#1

交叉表创建一个计数表:

pd.crosstab(df['Usernames'], df['Celebrity'])
#Celebrity  A  B  C  D
#Usernames            
#1          1  0  0  0
#2          1  0  1  1
#3          1  1  0  0

然后我们将其转换为真值表

pd.crosstab(df['Usernames'], df['Celebrity']).loc[:, ['A', 'C', 'D']].astype(bool)
#Celebrity     A      C      D
#Usernames                    
#1          True  False  False
#2          True   True   True
#3          True  False  False