Make a color pallet with Pandas Dataframe

Viewed 125

Let's say that I have a pandas data frame wherein some cells I have recorded an RGB value:

import pandas as pd
df = pd.DataFrame(index=[i for i in range(0,3)], columns=[i for i in range(0,3)])
df.at[1,1] = [0,0,1] #Blue
df.at[1,2] = [1,0,0] #Red
df.at[0,0] = [0,1,0] #Green

The data frame looks like this:

           0          1          2
0  [0, 1, 0]        NaN        NaN
1        NaN  [0, 0, 1]  [1, 0, 0]
2        NaN        NaN        NaN

Now, my question is: How can I make a plot from that, which should look like a grid of squares and where all NaN are plotted as white ?

1 Answers

Looks like you should be using numpy instead of pandas. Pandas is inherently a 2-d library, and by having lists in the cell, you're basically adding a third dimension. It looks like you could just have a 3-D numpy array where all NaNs should be [255, 255, 255]

e.g.

import matplotlib.pyplot as plt

white = [255, 255, 255]
arr = np.array([[[0, 1, 0], white, white],
                [white, [0, 0, 1], [1, 0, 0]],
                [white, white, white]])

>>> plt.imshow(arr)

enter image description here

The black squares all look the same and really black because the difference between [1, 0, 0] and [0, 0, 1] is not much from [0, 0, 0]. If you change them for more colored images, it gets easier to spot the difference:

enter image description here

arr = np.array([[[50, 111, 444], white, white],
                [white, [100, 200, 200], [100, 50, 0]],
                [white, white, white]])
Related