具有混合类型的Pandas DataFrame样式会产生TypeError

时间:2018-06-01 07:19:45

标签: python pandas dataframe

我有以下混合类型的DataFrame,我想仅在前4行为单元格着色:

>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(0)
>>> df = pd.DataFrame(index=[1,2,3,4],
                      columns = ['A','B'],             
                      data=np.random.uniform(low=0.,
                      high=1.,size=8).reshape(4,2)
                      )
>>> df = pd.concat([df,pd.DataFrame(index=[5],
                       columns=['A','B'],
                       data=[['OK', 'OK']])])
>>> df
           A           B
1   0.548814    0.715189
2   0.602763    0.544883
3   0.423655    0.645894
4   0.437587    0.891773
5         OK          OK

使用subset仅在前4行应用样式,这会给我一个错误:

>>> df.style.background_gradient(cmap='RdYlGn',
                         low=0.6, 
                         high=0.8, 
                         subset=pd.IndexSlice[1:4,:])
TypeError: ("Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'", 'occurred at index A')

任何解决方法的想法?

我正在使用Pandas 0.22.0

感谢, 格雷格

1 个答案:

答案 0 :(得分:1)

style尚不支持。

可能的解决方案是将非数字转换为NaN s:

df = df.apply(pd.to_numeric, errors='coerce')

如有必要,请突出显示:

df.style.background_gradient(cmap='RdYlGn',
                         low=0.6, 
                         high=0.8, 
                         subset=pd.IndexSlice[1:4,:]).highlight_null('red')

pic

相关问题