熊猫分组依据和筛选

时间:2020-03-17 23:44:19

标签: python pandas

我有以下.csv

  Name  Location    Product Type    number
Greg    1       Fruit   grape   1
Greg    1       Fruit   apple   2
Greg    1       Bakery  bread   5
Greg    1       Bakery  roll    8
Greg    2       Fruit   grape   7
Greg    2       Fruit   apple   1
Greg    3       Fruit   grape   2
Greg    4       Bakery  roll    3
Greg    4       Bakery  bread   4
Sam 5       Fruit   apple   7
Sam 5       Fruit   grape   9
Sam 5       Fruit   apple   10
Sam 6       Bakery  roll    11
Sam 6       Bakery  bread   12
Sam 7       Fruit   orange  13
Sam 7       Bakery  roll    14
Tim 8       Fruit   bread   16
Zack    9       Bakery  roll    17
Zack    10      Fruit   apple   19
Zack    10      Fruit   grape   20

我想把它放在大熊猫中并按名称分组,即在一个以上的地点有两种以上产品的地点。我仍然想保持产品的“数量”

像这样的例子,因为位置1的Greg有两个产品

name    location    product     type
Greg    1       Fruit, bakery   grape,apple,bread,roll

我正在与groupby苦苦挣扎,最终将其恢复到我可以.to_csv的数据帧中

2 个答案:

答案 0 :(得分:1)

IIUC将transformnunique一起使用

df1=df[df.groupby(['Name','Location']).Product.transform('nunique')>1]
    Name  Location Product    Type  number
0   Greg         1   Fruit   grape       1
1   Greg         1   Fruit   apple       2
2   Greg         1  Bakery   bread       5
3   Greg         1  Bakery    roll       8
14   Sam         7   Fruit  orange      13
15   Sam         7  Bakery    roll      14

答案 1 :(得分:0)

如果您执行df.groupby([col_names]),col_names将成为索引。

为了将索引转换回列,您需要使用DataFrame.reset_index()方法。

希望有帮助。