如何在Python中将字符串转换为数据帧

时间:2017-07-27 08:50:09

标签: python

我使用urlopen获取如下数据字符串。我想将字符串转换为数据框并保留多个列,如state,AQI等。我不知道该怎么做,想向你寻求建议。谢谢!

  response=urlopen(URL).read().decode('utf-8')
  print(response) 
"DateIssue","DateForecast","ReportingArea","StateCode","Latitude","Longitude","ParameterName","AQI","CategoryNumber","CategoryName","ActionDay","Discussion"
"2017-05-01 ","2017-05-01 ","Metropolitan Washington","DC","38.919","-77.013","O3","42","1","Good","false",""
"2017-05-01 ","2017-05-01 ","Metropolitan Washington","DC","38.919","-77.013","PM2.5","46","1","Good","false",""
"2017-05-01 ","2017-05-02 ","Metropolitan Washington","DC","38.919","-77.013","O3","44","1","Good","false",""
"2017-05-01 ","2017-05-02 ","Metropolitan Washington","DC","38.919","-77.013","PM2.5","25","1","Good","false",""
"2017-05-01 ","2017-05-03 ","Metropolitan Washington","DC","38.919","-77.013","O3","44","1","Good","false",""
"2017-05-01 ","2017-05-03 ","Metropolitan Washington","DC","38.919","-77.013","PM2.5","25","1","Good","false",""
"2017-05-01 ","2017-05-04 ","Metropolitan Washington","DC","38.919","-77.013","O3","42","1","Good","false",""
"2017-05-01 ","2017-05-04 ","Metropolitan Washington","DC","38.919","-77.013","PM2.5","29","1","Good","false",""

2 个答案:

答案 0 :(得分:7)

似乎你可以使用:

from pandas.compat import StringIO
df = pd.read_csv(StringIO(response))

但也许有效:

df = read_csv(URL)

答案 1 :(得分:3)

使用read_fwfto_csv(),然后read_csv()

import io 
import pandas as pd

df = pd.read_fwf(io.StringIO(response))

df.to_csv('data.csv')

result_df = pd.read_csv('data.csv',)