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 .
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.
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.
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.
Render a DataFrame to a console-friendly tabular output. Buffer to write to. If None, the output is returned as a string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With