Ad

Rearranging Data From A Table In Python To Correlate Columns

- 1 answer

I got a table that look like this:

codeyearmonthValue AValue B
120201120100
12020213090
1202039089
1202046765
...............
1002020109090
100202011115100
100202012150135

I would like to know if there's a way to rearrange the data to find the correlation between A and B for every distinct code.

What I'm thinking is, for example, getting an array for every code, like:

[(A1,A2,A3...,A12),(B1,B2,B3...,B12)]

where A and B is the values for the respective month, and then I could see the correlation between these two columns. Is there a way to make this dynamic?

Ad

Answer

IIUC, you don't need to re-arrange to get the correlation for each "code". Instead, try with groupby:

>>> df.groupby("code").apply(lambda x: x["Value A"].corr(x["Value B"]))
code
1      0.830163
100    0.977093
dtype: float64
Ad
source: stackoverflow.com
Ad