0

I have a dataframe which is generated from another dataframe by performing groupby operation using one column from the original df and another one a true/false vector generated again from a column of original df. Following code should reproduce that

import pandas as pd
import numpy as np

df=pd.DataFrame({'group1': list('AABBCCAABBCC'),'group2':list('ZYYXYXXYZXYZ'),'group3':list('MMMNNNOOOMNO'),'group4':list('EFGGFEEFGGFE')})
df['check_for_A']=df['group1']=='A' #True/False vector
truth_table=df.groupby(['group1','check_for_A']).group2.count().unstack().fillna(0)
truth_table['random_values']=np.random.rand(3)

The output looks like this

 check_for_A  False  True  random_values
 group1                                 
 A                0     4       0.917167
 B                4     0       0.965026
 C                4     0       0.046257

My problem is while I can access the column random_values by just typing truth_table['random_values'] , I cannot seem to access True or False columns. The command truth_table['True'] gives an error complaining something about the name True. Same thing happens with False. I a not sure why.

I think the problem IS with True/False name because if I do something like this

truth_table=df.groupby(['group1','group2']).group2.count().unstack().fillna(0)

Column names are x, y and z and I do not have any problems in accessing it.

I would appreciate if someone can explain this behavior and suggest alternative solution. I am thinking changing the column names but want to find out here what I am missing anyway.

1 Answer 1

3

You can access your data using truth_table[True] and truth_table[False] without the quotes. This can be seen if you do

print truth_table.columns
# Index([False, True, u'random_values'], dtype='object', name=u'check_for_A')

This behavior comes from the fact that the values in df['check_for_A'] are boolean and not strings.

2
  • Maybe you can add to answer print truth_table.columns is Index([False, True, u'random_values'], dtype='object', name=u'check_for_A')
    – jezrael
    Feb 20, 2016 at 8:54
  • Thanks @JulienSpronck and Jezrael. This was trivial but immensely helpful. Also, will help me watch out for strings/booleans in future.
    – PagMax
    Feb 20, 2016 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.