[SOLVED] Creating grid usonf Pandas for repetitive X-Y elements

Issue

I have a text file containing columns A,B and C with each row containing 1000+ elements as shown in image 1. Values in column C are output from a function with inputs as A and B.

Image 1

Most values in A and B are repetitive.

I want to create a grid as in image 2 using pandas such that the X-axis is A and Y-axis B with corresponding values as C. C should be output as a list of lists.

Image 2

I could not find a method for this. Request help.

Solution

I think you need to pivot your dataframe. Try:

out = df.pivot(index='A', columns='B', values='C')

But if you raise a ValueError about duplicate entries, it’s because you have more than one value for the same cell (A, B). In this case, you have to take a decision to keep only one value: you can take the mean, min, max, first, last or whatever you want that aggregate values.

Answered By – Corralien

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *