且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于多个标准的多列 pandas 计数

更新时间:2023-02-02 22:24:11

我分解步骤

df.columns=['TEXT','USER','ID']

df[word_list]=df.TEXT.str.lower().apply(lambda x : pd.Series([x.find(y) for y in word_list])).ne(-1)
df1=df[['USER','one','two','three','ID']].set_index(['USER','ID']).astype(int).replace({0:np.nan})
Target=df1.stack().reset_index().groupby('level_2').agg({'USER':lambda x : len(set(x)),'ID':lambda x : sum(set(x))})
Target=Target.reset_index()
Target.columns=['Word','Unique User Count','ID Sum']
Target
Out[97]: 
    Word  Unique User Count  ID Sum
0    one                  3     450
1  three                  1     150
2    two                  2     250