Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫根据索引名高亮显示行_Python_Pandas_Pandas Styles - Fatal编程技术网

Python 熊猫根据索引名高亮显示行

Python 熊猫根据索引名高亮显示行,python,pandas,pandas-styles,Python,Pandas,Pandas Styles,我一直在努力研究如何根据索引名设置行的样式。我知道如何高亮显示选定的行,但当我必须基于索引高亮显示时,代码不起作用 设置 df = pd.DataFrame({'key': list('ABCD'), 'value': range(4)}) print(df) key value 0 A 0 1 B 1 2 C 2 3 D 3 当键的值为“B”或“D”时突出显示行。 # this works df.style.apply(

我一直在努力研究如何根据索引名设置行的样式。我知道如何高亮显示选定的行,但当我必须基于索引高亮显示时,代码不起作用

设置

df = pd.DataFrame({'key': list('ABCD'), 'value': range(4)})
print(df)
  key  value
0   A      0
1   B      1
2   C      2
3   D      3
当键的值为“B”或“D”时突出显示行。

# this works

    df.style.apply(lambda x: ['background: lightgreen' 
                                          if (x.key == 'B' or x.key == 'D')
                                      else '' for i in x], axis=1)
根据索引名突出显示行

# This DOES NOT work
df1 = df.set_index('key')
df1.style.apply(lambda x: ['background: lightgreen' 
                                      if (x.index == 'B' or x.index == 'D')
                                      else '' for i in x], axis=1)

如何根据索引名称突出显示行?

索引更改为
名称

df1.style.apply(lambda x: ['background: lightgreen' 
                                  if (x.name == 'B' or x.name == 'D')
                                  else '' for i in x], axis=1)


当我们有一个名为“name”的列时,该怎么办?@astro123-然后通过
x['name']选择