pandas dataframe的两列唯一值

cur*_*one 12 python unique dataframe pandas

假设我有2列pandas数据框:

df: Col1  Col2
      1     1
      1     2
      1     2
      1     2
      3     4
      3     4
Run Code Online (Sandbox Code Playgroud)

然后我想只保留这两列的唯一值(col1,col2)并给出它们的频率:

df2: Col1  Col2  Freq
      1     1     1
      1     2     3
      3     4     2
Run Code Online (Sandbox Code Playgroud)

我想使用df['Col1', 'Col2'].value_counts()但它只适用于一列.它是否存在处理许多列的功能?

jez*_*ael 25

需要groupby+ size+ Series.reset_index:

df = df.groupby(['Col1', 'Col2']).size().reset_index(name='Freq')
print (df)
   Col1  Col2  Freq
0     1     1     1
1     1     2     3
2     3     4     2
Run Code Online (Sandbox Code Playgroud)


Qui*_*2k1 10

你可以试试

df.groupby(['Col1', 'Col2']).size()
Run Code Online (Sandbox Code Playgroud)

与 jez 的答案相比,对于不同的视觉输出,您可以扩展该解决方案

pd.DataFrame(df.groupby(['Col1', 'Col2']).size().rename('Freq'))
Run Code Online (Sandbox Code Playgroud)

           Freq
Col1 Col2      
1    1        1
     2        3
3    4        2
Run Code Online (Sandbox Code Playgroud)