Home > database >  Pandas - calculating difference in two hex integer color values
Pandas - calculating difference in two hex integer color values

Time:06-09

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

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.

CodePudding user response:

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
  • Related