簡體   English   中英

在熊貓中獲取數據框中重復行的所有ID

[英]Get all IDs of repeated rows in dataframe in Pandas

假設我們有一個具有重復行的數據框df 我想存儲唯一行的ID,以便每個行都有一個關聯的整數列表(它們在數據框中出現的ID)。

讓我舉一個例子:

import numpy as np
import pandas as pd

np.random.seed(0)
m = ['a','b']
M = ['X','Y']
n = np.arange(3)
size = 10
df = pd.DataFrame({'m': np.random.choice(m, size=size, replace=True),
                   'M': np.random.choice(M, size=size, replace=True),
                   'n': np.random.choice(n, size=size, replace=True)})

這將生成以下數據框:

   m  M  n
0  a  Y  2
1  b  X  2
2  b  X  0
3  a  Y  1
4  b  X  1
5  b  X  1
6  b  X  1
7  b  X  0
8  b  X  1
9  b  Y  0

我相信我想做類似df.groupby(df.columns.tolist()).size()事情,但是我不想獲取出現的次數,而是想要獲得它們出現的位置 因此,在這種情況下,所需的輸出將是(例如,以字典形式):

output = {('a','Y',1):[3],
          ('a','Y',2):[0],
          ('b','X',0):[2,7],
          ('b','X',1):[4,5,6,8],
          ('b','X',2):[1],
          ('b','Y',0):[9]
          }

我怎樣才能做到這一點? 這樣做的想法是盡可能地高效,因為數據框可以具有幾列和成千上萬(甚至幾百萬)行。

你有groups

df.groupby(list(df)).groups
Out[176]: 
{('a', 'Y', 1): Int64Index([3], dtype='int64'),
 ('a', 'Y', 2): Int64Index([0], dtype='int64'),
 ('b', 'X', 0): Int64Index([2, 7], dtype='int64'),
 ('b', 'X', 1): Int64Index([4, 5, 6, 8], dtype='int64'),
 ('b', 'X', 2): Int64Index([1], dtype='int64'),
 ('b', 'Y', 0): Int64Index([9], dtype='int64')}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM