将带逗号分隔数据和换行符的字符串转换为pandas dataframe

时间:2018-06-11 18:53:06

标签: python python-3.x pandas

我正在为股票拉1分钟的历史栏,数据如下:

'2018-06-11 09:31:00,968.250,965.000,968.000,965.250,17220,1160\n2018-06-11
09:32:00,965.250,964.250,965.250,964.750,17872,611\n2018-06-11
09:33:00,965.000,963.250,965.000,963.500,18851,547\n'

这是一个字符串,其中每一行由换行符分隔,每个字段用逗号分隔。当我使用print()函数时它看起来很好但我想将它转换为pandas数据帧。我感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

将字符串送入pandas.read_csv

时,此方法正常
import pandas as pd
from io import StringIO

mystr = StringIO("""2018-06-11 09:31:00,968.250,965.000,968.000,965.250,17220,1160\n2018-06-11 09:32:00,965.250,964.250,965.250,964.750,17872,611\n2018-06-11 09:33:00,965.000,963.250,965.000,963.500,18851,547\n""")

df = pd.read_csv(mystr, index_col=0, header=None)
df.index = pd.to_datetime(df.index)

print(df)

                          1       2       3       4      5     6
0                                                               
2018-06-11 09:31:00  968.25  965.00  968.00  965.25  17220  1160
2018-06-11 09:32:00  965.25  964.25  965.25  964.75  17872   611
2018-06-11 09:33:00  965.00  963.25  965.00  963.50  18851   547

print(df.dtypes)

1    float64
2    float64
3    float64
4    float64
5      int64
6      int64
dtype: object