0

I want to filter values across multiple columns creating dataframes for the unique value combinations. Any help would be appreciated.

Here is my code that is failing (given dataframe df):

dd = defaultdict(dict)  #create blank default dictionary
values_col1 = df.col1.unique()   #get the unique values from column 1 of df
for i in values_col1:
    dd[i] = df[(df['col1']==i)]    #for each unique value create a sorted df and put in in a dictionary
    values_col2 = dd[i].col2.unique() #get the unique values from column2 of df
    for m in values_col2:  
        dd[i][m] = dd[i][(dd[i]['col2']==m)]  #for each unique column2 create a sub dictionary

When I run it I get a very long error message. I won't insert the whole thing here, but here is some of it:

C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance) 1944 try: -> 1945 return self._engine.get_loc(key) 1946 except KeyError:

...

ValueError: Wrong number of items passed 6, placement implies 1

sparrow
  • 10,794
  • 12
  • 54
  • 74

1 Answers1

2

Use pandas groupby functionality to extract the unique indices and the corresponding rows of your dataframe.

import pandas as pd
from collections import defaultdict

df = pd.DataFrame({'col1': ['A']*4 + ['B']*4,
                   'col2': [0,1]*4,
                   'col3': np.arange(8),
                   'col4': np.arange(10, 18)})

dd = defaultdict(dict)
grouped = df.groupby(['col1', 'col2'])
for (c1, c2), g in grouped:
    dd[c1][c2] = g

This is the generated df:

  col1  col2  col3  col4
0    A     0     0    10
1    A     1     1    11
2    A     0     2    12
3    A     1     3    13
4    B     0     4    14
5    B     1     5    15
6    B     0     6    16
7    B     1     7    17

And this is the extracted dd (well, dict(dd) really)

{'B': {0:   col1  col2  col3  col4
          4    B     0     4    14
          6    B     0     6    16,
       1:   col1  col2  col3  col4
          5    B     1     5    15
          7    B     1     7    17},
 'A': {0:   col1  col2  col3  col4
          0    A     0     0    10
          2    A     0     2    12,
       1:   col1  col2  col3  col4
          1    A     1     1    11
          3    A     1     3    13}}

(I don't know what your use case for this is, but you may be better off not parsing the groupby object to a dictionary anyway).

Alicia Garcia-Raboso
  • 13,193
  • 1
  • 43
  • 48