7

I know that DataFrame can be be converted to string using to_string function:

import pandas as pd
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,
                   'B' : ['Aa', 'Bb', 'Cc'] * 4})
dfstr = df.to_string()
print(dfstr)

Output:

        A   B
0     one  Aa
1     one  Bb
2     two  Cc
3   three  Aa
4     one  Bb
5     one  Cc
6     two  Aa
7   three  Bb
8     one  Cc
9     one  Aa
10    two  Bb
11  three  Cc

How can I convert this dfstr back to a DataFrame object?


Edit:

I am asking specifically how the string created by df.to_string() function can be converted back to a dataframe object, not about general ways of converting text data (string) to dataframes as discussed on How to create a Pandas DataFrame from a string .

rnso
  • 23,686
  • 25
  • 112
  • 234
  • The `.to_csv()` method of pandas dataframes will return the would be contents of the csv file as a string if no file path is included as an argument. The returned string can be read with `io.StringIO()` and `pd.read_csv()` with no special arguments. I don't know why you want to use the `.to_string()` method, but in almost every circumstance in which you want to output a string that can later be read as a csv `.to_csv()` without a file path argument is the best option. – zozo Jul 30 '18 at 08:14
  • Looks very good suggestion. You should add this as an answer. – rnso Jul 30 '18 at 13:48

1 Answers1

9

Use read_csv with StringIO:

from pandas.compat import StringIO #if this doesn't work try: from io import StringIO

df = pd.read_csv(StringIO(dfstr), sep='\s+')
print (df)

        A   B
0     one  Aa
1     one  Bb
2     two  Cc
3   three  Aa
4     one  Bb
5     one  Cc
6     two  Aa
7   three  Bb
8     one  Cc
9     one  Aa
10    two  Bb
11  three  Cc
Yehla
  • 199
  • 11
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Is there any reason not to close this as a duplicate of one of the many similar questions in the past? The first one which I found was [this](https://stackoverflow.com/questions/22604564/how-to-create-a-pandas-dataframe-from-a-string). – DSM Dec 01 '17 at 15:31
  • @DSM - so sorry, if think so, no problem if close question. – jezrael Dec 01 '17 at 15:33