Home > Mobile >  How do I cross time series in pandas?
How do I cross time series in pandas?

Time:11-27

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.

CodePudding user response:

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
  • Related