Search code examples
pythonpandasdataframereverse-engineering

How do I reverse a DataFrame back to its Code form?


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.


Solution

  • 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]}