0

Am trying to get the occurrences of certain pattern based on Index in Dataframe , any help would be appreciated

Have manually added a column as Index and need to get occurrences of pattern based on Index and the column



dataset sample      
a(index)    d   
pattern 1   test    
pattern 1   test    
pattern 1   test2   
pattern 2   test3   
pattern 2   test    
pattern 2   test    

expected output     

Am looking to make a dataframe something like below with the above sample data

pattern  test test2 test3
----------------------------------
pattern 1   2   1        0
pattern 2   2   0        1

3
  • 2
    df.groupby(['a','d']).count().reset_index(name='Count') Commented Aug 13, 2019 at 4:47
  • 1
    If a is index, try df.groupby([df.index, 'd']).count().reset_index() Commented Aug 13, 2019 at 4:48
  • Thanks for the quick update , have re-phased the question.. seems i did not express correctly. Any suggestion here would be helpful. Am trying to understand % of certain pre-defined value based on pattern Commented Aug 13, 2019 at 7:00

1 Answer 1

1

If you reset the index, it's a pretty straightforward groupby:

In [18]: df
Out[18]:
               d
a
pattern 1   test
pattern 1   test
pattern 1  test2
pattern 2  test3
pattern 2   test
pattern 2   test

In [19]: df.reset_index().groupby(['a', 'd']).apply(len).reset_index()
Out[19]:
           a      d  0
0  pattern 1   test  2
1  pattern 1  test2  1
2  pattern 2   test  2
3  pattern 2  test3  1
Sign up to request clarification or add additional context in comments.

1 Comment

Have re-phrased the question , please have a look and let me know if this is feasible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.