Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string from df.to_string() back to DataFrame [duplicate]

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 .

like image 945
rnso Avatar asked Dec 01 '17 15:12

rnso


People also ask

How do you turn a string into a DataFrame?

If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.

Can we convert a string to DataFrame in Python?

Use pandas. read_csv() to create a DataFrame from a string Use io. StringIO(string) with string as a string of data to get a StringIO object. To create a DataFrame , use pandas.

What does DF copy () do?

Pandas DataFrame copy() Method The copy() method returns a copy of the DataFrame. By default, the copy is a "deep copy" meaning that any changes made in the original DataFrame will NOT be reflected in the copy.

What is the use of To_string in Python?

Render a DataFrame to a console-friendly tabular output. Buffer to write to. If None, the output is returned as a string.


1 Answers

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
like image 198
jezrael Avatar answered Sep 26 '22 02:09

jezrael