Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas – calculating difference in two hex integer color values

I am attempting to calculate differences in integer hex values. My df as formatted as such:

import pandas as pd

data = [['0xD8E3ED', 2043441], ['0xF7F4EB', 912788],['0x000000',6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])
df['value'] = df['c_code'].apply(int, base=16)

Now I would like to add a color difference to my df with help from

coldiff.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am able to run the following with success

(cie94(rgb2lab(rgb(13227184)), rgb2lab(rgb(14214125))))
18.41431752537279

(cie94(rgb2lab(rgb(13227184)), rgb2lab(rgb(df['value'].iloc[0]))))
18.41431752537279

But when I attempt to run through the rows of my dataframe I get the following error

df['diff'] = (cie94(rgb2lab(rgb(13227184)), rgb2lab(rgb(df['value']))))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-521a6c3f607f> in <module>
----> 1 df['diff'] = (cie94(rgb2lab(rgb(13227184)), rgb2lab(rgb(df['value']))))
      2 df

<ipython-input-2-ce2d615c99ef> in rgb(x)
     40     if isinstance(x, str) and x[0] == '#':
     41         x = int(x[1:], 16)
---> 42     return ((x >> 16) & 0xff, (x >> 8) & 0xff, (x) & 0xff)
     43 
     44 

TypeError: unsupported operand type(s) for >>: 'Series' and 'int'

I believe that this is from the df rows not being read in as integers but I am unsure of how to resolve it or why .iloc[0] seems to solve the issue. I have tried running as a loop with .iloc[i] but cannot seem to resolve the issue. Additionally, using a .apply(int) method within rgb() produces the same error.

>Solution :

You can do a row-by-row evaluation using apply with axis=1:

df.apply(lambda x: (cie94(rgb2lab(rgb(13227184)), rgb2lab(rgb(x['value'])))), axis=1)

0    18.414318
1    15.444622
2    83.892102
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading