简体   繁体   English

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

[英]Converting string with comma delimited data and newline character to pandas dataframe

I'm pulling 1 minute historical bars for a stock and the data comes in like this: 我正在为某股票拉入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'

It's one string where each row is separated by the new line character and each field is separated by a comma. 这是一个字符串,其中的每一行都由换行符分隔,而每个字段均由逗号分隔。 It looks fine when I use the print() function but I want to convert this into a pandas dataframe. 使用print()函数时看起来不错,但我想将其转换为pandas数据框。 I appreciate any help. 感谢您的帮助。

This works fine when feeding the string to pandas.read_csv : 将字符串输入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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将具有键值形式的逗号分隔字符串转换为 pandas Dataframe - Converting comma separated string with key-value form into pandas Dataframe 在Python中将一列spark数据帧转换为由pipline字符分隔的Single String - Converting one column spark dataframe into Single String delimited by pipline character in Python pandas/regex: 去掉连字符或括号字符后的字符串(包括) carry string in the comma after the comma in pandas dataframe - pandas/regex: Remove the string after the hyphen or parenthesis character (including) carry string after the comma in pandas dataframe 将Pandas Dataframe转换为以逗号浮动时出错 - Error Converting Pandas Dataframe to float with comma 在逗号分隔的文本文件中查找一个字符,并返回它所属的字符串 - Find a character in a comma delimited text file, and return the string it belongs to 将字符串转换为熊猫数据框的条件 - Converting string into condition for pandas dataframe 在pandas数据帧中将float转换为字符串 - Converting float to string in pandas dataframe 使用表情符号将熊猫数据框转换为字符串 - Converting pandas dataframe to string with emojis 如何将制表符分隔为以逗号分隔的熊猫 - How to change tab delimited in to comma delimited in pandas 在Python中将JSON转换为换行符分隔的JSON - Converting JSON into newline delimited JSON in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM