3

I want to be able to reverse a dataframe back to its code form.

So we know that that this code form:

dat=pd.DataFrame(dict(Date=['19/11/2012', '20/11/2012', '21/11/2012'],
                    A=[1,3,1],
                    B=[3,2,2],
                    C=[4,3,2],
                    D=[5,2,2],))

gives results in a DataFrame being created that looks like:

+---+------------+---+---+---+---+
|   |    Date    | A | B | C | D |
+---+------------+---+---+---+---+
| 0 | 19/11/2012 | 1 | 3 | 4 | 5 |
| 1 | 20/11/2012 | 3 | 2 | 3 | 2 |
| 2 | 21/11/2012 | 1 | 2 | 2 | 2 |
+---+------------+---+---+---+---+

However, is there a way for me to convert a DataFrame above back to its code form? In the example above, I knew the code to create the DataFrame beforehand, however, in reality I wouldn't have that information.

crickcrock
  • 113
  • 6
  • you can have multiple ways of "making" a dataframe. So going from output to input is a one to many relationship. So think of it in a different way instead: How can i get the information out of a dataframe so that i can make that same dataframe again? And then just pick one of the many options. – Paritosh Singh Nov 22 '19 at 12:44

1 Answers1

5

Try pandas.DataFrame.to_dict():

>>> dat=pd.DataFrame(dict(Date=['19/11/2012', '20/11/2012', '21/11/2012'],
                    A=[1,3,1],
                    B=[3,2,2],
                    C=[4,3,2],
                    D=[5,2,2],))
>>> dat
         Date  A  B  C  D
0  19/11/2012  1  3  4  5
1  20/11/2012  3  2  3  2
2  21/11/2012  1  2  2  2

>>> dat.to_dict(orient = 'list')
{'Date': ['19/11/2012', '20/11/2012', '21/11/2012'],
 'A': [1, 3, 1],
 'B': [3, 2, 2],
 'C': [4, 3, 2],
 'D': [5, 2, 2]}
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • 1
    It should also be kept in mind that for each possible final state of the `DataFrame` there are inumerous ways in which one could populate and manipulate to reach that final state. Turning the `DataFrame` into a dictionary would only capture that final state. – Haroldo_OK Nov 22 '19 at 12:44
  • @Haroldo_OK Agreed. – Sayandip Dutta Nov 22 '19 at 12:45