Home > Net >  Receiving error while trying to highlight a row with .style Pd DataFrame
Receiving error while trying to highlight a row with .style Pd DataFrame

Time:04-19

I have the following code for trying to highlight a certain row in my dataframe.

# morphological features in WALS
wals_morph_features = pd.DataFrame({'Feature Name': ['Fusion of Selected Inflectional Formatives', 'Exponence of Selected Inflectional Formatives', 'Exponence of Tense-Aspect-Mood Inflection', 'Inflectional Synthesis of the Verb', 'Locus of Marking in the Clause', 'Locus of Marking in Possessive Noun Phrases', 'Locus of Marking: Whole-language Typology', 'Zero Marking of A and P Arguments', 'Prefixing vs. Suffixing in Inflectional Morphology Prefixing vs. Suffixing in Inflectional Morphology', 'Reduplication', 'Case Syncretism', 'Syncretism in Verbal Person/Number Marking'],
                                    'Feature ID': ['20A', '21A', '21B', '22A', '23A', '24A', '25A', '25B', '26A', '27A', '28A', '29A'],
                                  'Number of Languages': ['165', '162', '160', '145', '236', '236', '236', '235', '969', '368', '198', '198'],
                                  'Number of Variances': ['7', '5', '6', '7', '5', '6', '5', '2', '6', '3', '4', '3']})


def custom_style(row):

    color = 'white'
    if row.values[-1] == 'Locus of Marking in Possessive Noun Phrases':
        color = 'yellow'

    return ['background-color: %s' % color]*len(row.values)

wals_morph_features.styler.apply(custom_style, axis=1)

wals_morph_features

However, I am receiving the error AttributeError: 'DataFrame' object has no attribute 'styler'

I'm not sure what's wrong as the documentation is saying this is the correct syntax.

CodePudding user response:

It should read

wals_morph_features.style.apply(custom_style, axis=1)

instead of

wals_morph_features.styler.apply(custom_style, axis=1),

i.e., the attribute is style and not styler.

CodePudding user response:

You can try this way: choose the colors you like: Disclosure: this answer was orignally answered elsewhere in stackoverflow.

def red_or_green(dataframe):
    row = dataframe['Feature Name'] == 'Locus of Marking in Possessive Noun Phrases'
    a = np.where(np.repeat(row.to_numpy()[:,None],dataframe.shape[1],axis=1),
                 'background-color: white','background-color: #222222')
    return pd.DataFrame(a,columns=dataframe.columns,index=dataframe.index)

wals_morph_features.style.apply(red_or_green, axis=None)

  • Related