如何在Python中将字符串转换为数据框[重复]
Posted
技术标签:
【中文标题】如何在Python中将字符串转换为数据框[重复]【英文标题】:How to convert a string to a dataframe in Python [duplicate] 【发布时间】:2018-01-02 21:17:15 【问题描述】:我使用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",""
【问题讨论】:
【参考方案1】:使用read_fwf 和to_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',)
【讨论】:
谢谢你拯救了我的一天【参考方案2】:看来你可以使用:
from pandas.compat import StringIO
df = pd.read_csv(StringIO(response))
但也许也可以:
df = read_csv(URL)
【讨论】:
以上是关于如何在Python中将字符串转换为数据框[重复]的主要内容,如果未能解决你的问题,请参考以下文章