Why does decimal doesn't work when creating pivot table in pandas?

Viewed 115

The following works fine:

a = pandas.DataFrame({
    'A': ['a', 'b', 'a'],
    'B': ['one', 'two', 'three'],
    'C': [22.3, 34.0, 12.3]
})

pandas.pivot_table(a, values='C', index='A', columns='B')

B   one  three   two
A                   
a  22.3   12.3   NaN
b   NaN    NaN  34.0

But the following returns an empty data frame when pivoted and I am wondering why that is the case:

b = pandas.DataFrame({
    'A': ['a', 'b', 'a'],
    'B': ['one', 'two', 'three'],
    'C': [decimal.Decimal('22.3'), decimal.Decimal('34.0'), decimal.Decimal('12.3')]
})

pandas.pivot_table(b, values='C', index='A', columns='B')
                                             
Empty DataFrame
Columns: []
Index: [a, b]

1 Answers

b.C has its dtype as object. Convert it to numeric and it should work as expected.

b.C = pandas.to_numeric(b.C)
print(pandas.pivot_table(b, values='C', index='A', columns='B'))
Related