简体   繁体   中英

Using 'If' functions in a 'For' loop over Pandas DataFrames?

So I have this Pandas DataFrame.

DataFrame

I am trying to figure out how to write this in python.

For each row I want to say, "if the 'Bid_Size' is a different value that the 'Bid_Size' in the previous row, highlight this cell.

For instance in my provided data set, row #3/column-'Bid_Size' would be highlighted because it is a different value than the 'Bid_Size' in the previous row.

I am guessing it would go something like

import pandas as pd
file = pd.read_csv('DataBase.csv', header=None, names=['Book_ID','Asset','Best_Bid','Bid_Size','Best_Ask', 'Ask_Size'])  

df = pd.DataFrame(file)

def highlight_yellow(df):
    for rows in df:
        if df['Best_Bid'] != -['Best_Bid']:
            return['highlight:yellow']

df.style.apply(highlight_yellow)

Thank you, I just can not figure this one out.

You could shift Best_Bid down one and then compare to assign a value. First create a highlight column with your default value, then reassign.

>>> df=pd.DataFrame({"Best_Bid":[1,1,1,2,2,5,1,5,4,4,4]})
>>> df["Highlight"] = ""
>>> df["Highlight"][df["Best_Bid"] != df["Best_Bid"].shift(1)] = "highlight:yellow"
>>> df
    Best_Bid         Highlight
0          1  highlight:yellow
1          1                  
2          1                  
3          2  highlight:yellow
4          2                  
5          5  highlight:yellow
6          1  highlight:yellow
7          5  highlight:yellow
8          4  highlight:yellow
9          4                  
10         4                  

I don't know what kind of data you have, but I will make an example. Suppose that you have this dataframe:

import pandas as pd

df = pd.DataFrame({
    'Best_Bid' : ['value_a', 'value_b', 'value_a','value_a']
})

Now create a function to paint your rows:

 def highlight(column_value, value_to_compare):
    color_a = 'background-color: yellow'
    color_b = 'background-color: red'
    return color_a if column_value==value_to_compare else color_b

Now, apply this function:

df.style.applymap(lambda x: highlight(x, "value_a"))

And you will get:

在此处输入图像描述

This function will allow you to handle your color and indexes in an independent way!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM