Skip to content
Advertisement

How to convert a pandas dataframe column to an image array i.e. a numpy array with shape (n,n) in Python?

Suppose my dataframe has 750 rows in a column and I want to convert that column to an image array of (20,20) numpy array. How to do that?

EDIT1: I want to use the array for ax.contourf (x,y,z) as z. I got x,y by doing x,y=np.meshgrid(df3.x,df.y) now I want to convert another column to an (n,n) array to vary the colors inside the contours using the z parameter.

EDIT2:x,y,z Data to plot contour plot

Advertisement

Answer

Given the fact that you have x and y as columns already, I would use pivot_table like this :

JavaScript

The beauty of pivot_table is that this will sort your x/y values.

Be carefull though, your y value would be ascending (top to bottom), which is the opposite of what you would want in a picture. You have to re-sort the index in reverse mode (hence the sort_index command).

There is also an assumption here : that your x’s and y’s values are linear OR that you are not trying to plot anything linear. In fact, you data sample are not (for instance, your first discrete y values are 3.5, 4, 4.1) ; you simply cannot use that kind of coordinates for anything in a grid format.

Given the fact that your datas’ coordinates are all float with one decimal (at most), you could complete your datas this way :

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement