Find unique values โ€‹โ€‹in a Pandas frame, regardless of row or column location

I have a Pandas framework and I want to find all the unique values โ€‹โ€‹in this data frame ... regardless of the row / columns. If I have 10 x 10 data frames and suppose they have 84 unique values, I need to find them - Do not count.

I can create a set and add the values โ€‹โ€‹of each row by iterating over the rows of data. But I feel that this may be ineffective (cannot justify it). Is there an effective way to find it? Is there a predefined function?

+48
python pandas dataframe
Nov 19 '13 at 23:26
source share
2 answers
In [1]: df = DataFrame(np.random.randint(0,10,size=100).reshape(10,10)) In [2]: df Out[2]: 0 1 2 3 4 5 6 7 8 9 0 2 2 3 2 6 1 9 9 3 3 1 1 2 5 8 5 2 5 0 6 3 2 0 7 0 7 5 5 9 1 0 3 3 5 3 2 3 7 6 8 3 8 4 4 8 0 2 2 3 9 7 1 2 7 5 3 2 8 5 6 4 3 7 0 8 6 4 2 6 5 3 3 4 5 3 2 7 7 6 0 6 6 7 1 7 5 1 8 7 4 3 1 0 6 9 7 7 3 9 5 3 4 5 2 0 8 6 4 7 In [13]: Series(df.values.ravel()).unique() Out[13]: array([9, 1, 4, 6, 0, 7, 5, 8, 3, 2]) 

Numpy is unique varieties, so its faster to do it this way (and then sort if you need to)

 In [14]: df = DataFrame(np.random.randint(0,10,size=10000).reshape(100,100)) In [15]: %timeit Series(df.values.ravel()).unique() 10000 loops, best of 3: 137 ๏พตs per loop In [16]: %timeit np.unique(df.values.ravel()) 1000 loops, best of 3: 270 ๏พตs per loop 
+71
Nov 20 '13 at
source share

Or you can use:

df.stack().unique()

Then you need not worry if you have NaN values, as they are excluded when performing stacking.

+4
Mar 10 '17 at 9:19 on
source share



All Articles