1
$\begingroup$

I have a pandas dataframe with a column CAS_BRM_IDA of type category (even if its values seem of foat type ... but they are not meaningful per se)

I built the following serie from that dataframe :

p = df.groupby( [ 'CAS_BRM_IDA' ] ).mean()[ 'TOP_FRD']
print( p )

Result displayed :

CAS_BRM_IDA
10.0       0.001131
13.0       0.000000
15.0       0.002038
17.0       0.000000
20.0       0.003802
...
missing    0.019549

I then tried to build a dictionary using that serie :

mydic = dict( [ ( i , p[i] ) for i in p.index ] )

But I got the following error message :

TypeError: cannot do label indexing on
  <class 'pandas.core.indexes.category.CategoricalIndex'>
   with these indexers [10.0] of <class 'float'>

Some details about the p index :

CategoricalIndex(
    [10.0, 13.0, 15.0, 17.0, 20.0, 21.0, 30.0, 31.0, 40.0, 43.0,
     50.0, 51.0, 56.0, 'missing'],
     categories=[10.0, 13.0, 15.0, 17.0, 20.0, 21.0, 30.0, 31.0, ...],
     ordered=False, name='CAS_BRM_IDA', dtype='category')

I can't figure out where is the problem. '10.0' value seems to have been interpreted as float which I thought it's not.

How can I build a dict from a Series with a Categorical Index which contains floats?

$\endgroup$
2
$\begingroup$

Try the intrinsic pandas conversion:

p.to_dict()
$\endgroup$
  • $\begingroup$ It worked just fine. I did not know that syntax. Thanks. $\endgroup$ – Fabrice BOUCHAREL May 8 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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