4

I have two Pandas dataframes like the ones below (sample code given here).

                   A         B         C         D
2000-01-01  0.298399 -0.738440 -0.505438  0.324951
2000-01-02  1.300686 -0.938543 -1.850977  0.868467

and

                   A         B         C         D
2000-01-03  0.328032  0.325845 -0.289175  0.393732
2000-01-04  0.091853 -1.450642 -0.544152  1.073248

and I would like to zip them so I can process their values. To clarify, I am trying to take two rows at a time — by zipping the corresponding rows together. I do not want to create a new df unless it would be more efficient that way.


I did the first thing that came to mind, i.e.,

for i, (x, y) in enumerate(zip(df1, df2)):
    print(i, x, y)

and expected to get something like:

0 (0.298399 -0.738440 -0.505438  0.324951) (0.328032  0.325845 -0.289175  0.393732)
1 (1.300686 -0.938543 -1.850977  0.868467) (0.091853 -1.450642 -0.544152  1.073248)

but what I got was:

0 A A
1 B B

How can one get the typical zip behavior when working with dataframes?

Surprisingly, I could not find a duplicate for my question since both this and this are asking something different.

cs95
  • 379,657
  • 97
  • 704
  • 746
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • Possible duplicate of [Zip pandas dataframes into a new dataframe](https://stackoverflow.com/questions/34318141/zip-pandas-dataframes-into-a-new-dataframe) – IT World Jan 23 '19 at 09:15
  • @ITWorld I already saw this and it is not what I am trying to do (*"I do not want to create a new df..."*). – Ma0 Jan 23 '19 at 09:16
  • "so I can process their values" what do you plan on doing? – cs95 Jan 23 '19 at 09:18
  • @coldspeed The values are then used to construct symbolic equations with `sympy`. – Ma0 Jan 23 '19 at 09:20
  • Okay, and you are trying to zip two rows together? – cs95 Jan 23 '19 at 09:20
  • @coldspeed Is that not clear from the question? ☺ – Ma0 Jan 23 '19 at 09:21
  • No, not exactly. Or maybe I'm just tired. Anyway, I expected to see something like "I am trying to zip the rows together" but all I see was "zip two DataFrames", and I was not sure what you were referring to when you said "typical zip behaviour". – cs95 Jan 23 '19 at 09:23
  • @coldspeed Or maybe I am. Anyway, feel free to edit it to make it more clear if it is misleading. – Ma0 Jan 23 '19 at 09:25

1 Answers1

5

You can convert DataFrames to numpy arrays:

for i, (x, y) in enumerate(zip(df1.values, df2.values)):
    print(i, x, y)

Your solution return columns names, becuse is processes like:

for i, (x, y) in enumerate(zip(df1.columns, df2.columns)):
    print(i, x, y)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252