[英]python pandas dataframe color the text as red, green or black in column based on the condition from the other column
I have a pandas dataframe which looks like this:我有一个看起来像这样的熊猫数据框:
ID CNTS neg pos neu comp Overall
1 Reliance Jio Infocomm has accused Bharti Airtel, Vodafone Idea and BSNL of 'cheating' by fraudulently masquerading landline numbers as mobile numbers to unfairly earn interconnect revenue. 0.081 0 0.919 -0.296 Negative
1 The accusation adds new twist to the ongoing telecom tussle. 0.182 0 0.818 -0.25 Negative
1 Here's what is making India's richest man angry. 0.26 0.268 0.472 0.0258 Neutral
2 Jio wants Trai to slap the heaviest penalties on both rivals & BSNL for flouting rules, which it claims cost the company hundreds of crores. 0 0.065 0.935 0.1531 Positive
2 It has also sought a refund of the termination charges it had paid the incumbents due to the alleged fraud. 0.258 0 0.742 -0.7096 Negative
2 Jio claims Airtel, Vodafone Idea and BSNL have implemented a process under which various enterprises are offered mobile numbers as their customer care or helpline numbers. 0 0.118 0.882 0.4939 Positive
Also I wrote a function which returns the specific color based on the values of the dataframe column name "Overall":我还编写了一个函数,该函数根据数据框列名称“总体”的值返回特定颜色:
def cts(val):
if (val == 'Negative'):
color = 'red'
elif (val == "Positive"):
color = 'green'
else:
color = 'black'
return 'color: %s' % color
Now what I want to do that, using the color, the text in the column "CNTS" should get formatted accordingly.现在我想做的是,使用颜色,“CNTS”列中的文本应该相应地格式化。
I was trying something which I read on Pandas documentation site:我正在尝试在 Pandas 文档网站上阅读的内容:
# Apply color
s = df.style.applymap(cts)
s
But it obviously threw an error.但它显然抛出了一个错误。 But I don't have any clue or idea how I could apply the function to achieve what I wanted to have as.但我没有任何线索或想法如何应用该功能来实现我想要的。 Could someone help please?有人可以帮忙吗?
Use custom function with Series.map
for filling column by dictionary of colors:使用带有Series.map
自定义函数通过颜色字典填充列:
df = pd.DataFrame({'Overall':['Negative','Positive','Another'],
'CNT':list('abc')})
def cts(x):
c1 = 'color: red'
c2 = 'color: green'
d = {'Negative':c1, 'Positive':c2}
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
df1['CNT'] = x['Overall'].map(d).fillna('color: black')
return df1
df.style.apply(cts, axis=None)
Sample :样品:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.