1

Is there a way to get a textual representation of a dataframe that I can just paste back into the repl, but that still looks good as a table? Numpy repr manages this pretty well, I'm talking something like:

> df
   A  B  C
i         
0  3  1  8
1  3  1  6
2  7  4  6
> df.to_python()
DataFrame(
columns=['i',  'A', 'B', 'C'],
data = [[  0,   30,   1,   8],
        [  1,    3,   1,   6],
        [  2,    7,   4,   6]]
).set_index('i')

This seems like it would be especially useful for stack overflow, but I often find myself needing to share small dataframes and would love it if this were possible.

Edit: I know about to_csv and to_dict and so on, what I want is a way of exactly reproducing a dataframe that also can be read as a table. It seems that this probably doesn't have a current answer (although I'd love to see pandas add it), but I think I can make pd.read_clipboard('\s\s+') work for 95% of my usages.

U2EF1
  • 12,907
  • 3
  • 35
  • 37
  • I asked a similar, but broader, question [here](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples), got a good answer but nothing that was equivalent to Numpy's `repr` or R's `dput()`. – Marius Jul 16 '14 at 00:05
  • @Marius Based on that it seems like a lot of the text tables can be read pretty easily with `pd.read_clipboard('\s\s+')`, although it can discard some info and isn't a strict inverse of `df.to_clipboard()`. @Andy-Hayden's answer was excellent. – U2EF1 Jul 16 '14 at 00:34

2 Answers2

1

StringIO tells python to treat a string as a filelike object which allows you to use the read_csv method example below...

df = """   A  B  C
i
0  3  1  8
1  3  1  6
2  7  4  6"""#this is equivalent to str(df) or what happens when you use print df

df = pd.read_csv(StringIO.StringIO(df),sep="\s*",engine = 'python')
ZJS
  • 3,991
  • 2
  • 15
  • 22
0

df.to_dict() will get you close, although you do lose the index name:

df.to_dict()
Out[5]: {'A': {0: 30, 1: 3, 2: 7}, 'B': {0: 1, 1: 1, 2: 4}, 'C': {0: 8, 1: 6, 2: 6}}

df_copy = pd.DataFrame(df.to_dict())

df_copy
Out[7]: 
    A  B  C
0  30  1  8
1   3  1  6
2   7  4  6
Marius
  • 58,213
  • 16
  • 107
  • 105