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

时间:2017-12-01 15:24:43

标签: python string python-3.x pandas dataframe

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

post

输出:

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

如何将此 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 转换回DataFrame对象?

编辑:

我具体询问如何将dfstr函数创建的字符串转换回数据框对象,而不是如How to create a Pandas DataFrame from a string所讨论的那样将文本数据(字符串)转换为数据帧的一般方法。< / p>

1 个答案:

答案 0 :(得分:3)

read_csvStringIO

一起使用
from pandas.compat 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