数据帧按特定值分组

2024-04-19 23:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个事务数据帧,如下所示:

+----------+----------+----------+---------+
|  Owner   |  Seller  | Mediator |  Buyer  |
+----------+----------+----------+---------+
| 'andrew' | 'bob'    | 'tom'    | 'john'  |
| 'andrew' | 'andrew' | 'bill'   | 'jason' |
| 'andrew' | 'bill'   |  'bill'  | 'tom'   |
+----------+----------+----------+---------+

我想执行一个奇怪的groupby-我想根据参与交易的人的名字进行分组。所以输出是:

+----------+-------+
|   Name   | Count |
+----------+-------+
| 'andrew' |     3 |
| 'bob'    |     1 |
| 'tom'    |     2 |
| 'john'   |     1 |
| 'bill'   |     2 |
| 'jason'  |     1 |
+----------+-------+

例如,“andrew”的计数是3,因为他的名字出现在3个事务中,“john”的计数是1,因为他只出现在1中,以此类推

做这个有什么建议吗?提前谢谢


Tags: 数据buyer名字john事务计数bobgroupby
3条回答

您可以从每一行创建一个集合,然后重塑为垂直数据堆栈并获取值计数。你知道吗

import pandas as pd

df = pd.DataFrame({'Owner': ['andrew', 'andrew', 'andrew'],
 'Seller': ['bob', 'andrew', 'bill'],
 'Mediator': ['tom', 'bill', 'bill'],
 'Buyer': ['john', 'jason', 'tom']}
)

cnt = (
    df.apply(lambda r: pd.Series(list(set(r))), axis=1)
      .stack()
      .value_counts()
      .reset_index().rename(columns={'index': 'Name', 0: 'Count'})
)
cnt
# returns:
     Name  Count
0  andrew      3
1    bill      2
2     tom      2
3   jason      1
4    john      1
5     bob      1

具有“unique()”的解决方案:

df.apply(lambda row: row.unique(),axis=1) \
  .explode().value_counts() \
  .to_frame(name="Count")  \
  .rename_axis(["Name"])      

        Count
Name         
andrew      3
bill        2
tom         2
john        1
bob         1
jason       1

您可以使用unstack()来:

  1. 将所有名称放在一列中
  2. 分组依据Name和计数unique original-index,即level_1之后的unstack()reset_index()
    (df.unstack()
       .reset_index(name='Name')
       .groupby('Name') 
       .level_1 
       .nunique() 
       .rename('Count') 
       .reset_index())

    #Out[xx]:
    #     Name  Count
    #0  andrew      3
    #1    bill      2
    #2     bob      1
    #3   jason      1
    #4    john      1
    #5     tom      2

相关问题 更多 >