How do I cross time series in pandas?

Question:

Let’s say I’ve got a dataframe with an integer index:

pd.DataFrame([[4,5],[7,8],[9,10]],columns=['a','b'])

    a   b
0   4   5
1   7   8
2   9   10

I’d like to create a matrix of ratios for each of a cross b, for each index, so I get a series of matrices of the form:

a/a a/b
b/a b/b

for each index. Ultimately, I’ll want to unfurl these into four columns.

Is there an easy way? If there’s an easy numpy solution doing this, that might be better.

Asked By: cjm2671

||

Answers:

Easy way:

pd.DataFrame({f'{x}/{y}': df[x] / df[y] for x in df for y in df})

Slightly complicated way (might be faster if you have large number of columns):

a = df.values[None].T / df.values
pd.DataFrame(np.hstack(a), columns=(f'{x}/{y}' for x in df for y in df))

Result

   a/a    a/b       b/a  b/b
0  1.0  0.800  1.250000  1.0
1  1.0  0.875  1.142857  1.0
2  1.0  0.900  1.111111  1.0
Answered By: Shubham Sharma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.