如何将字符串从 df.to_string() 转换回 DataFrame

rns*_*nso 4 python string dataframe python-3.x pandas

我知道可以使用 to_string 函数将 DataFrame 转换为字符串:

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

输出:

        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
Run Code Online (Sandbox Code Playgroud)

如何将其转换dfstr回 DataFrame 对象?


编辑:

我特别询问如何将df.to_string()函数创建的字符串转换回数据帧对象,而不是关于如何将文本数据(字符串)转换为数据帧的一般方法,如如何从字符串创建 Pandas DataFrame 中所讨论的。

jez*_*ael 6

使用read_csvStringIO

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
Run Code Online (Sandbox Code Playgroud)