【发布时间】:2015-03-24 11:30:30
【问题描述】:
我正在从网站检索多个 csv 格式的数据帧。我将数据框保存在一个空列表中,然后一一读取。我无法将它们附加到单个数据框中,因为它们具有不同的列名和列顺序。所以我有以下问题:
我可以在用于读取文件的循环内创建一个具有不同名称的数据框,而不是将它们保存到列表中,而是为每个检索到的文件创建一个新的数据框?如果这是不可能的/推荐的,有没有办法迭代我的列表来提取数据框?目前我当时读了一个数据帧,但我很想想出一种方法来自动化这个代码来创建像 data_1、data_2 等的东西。现在我的代码并不是非常耗时,因为我只有 4 个数据帧,但是随着数据的增多,这可能会变得很麻烦。这是我的代码:
import pandas as pd
import urllib2
import csv
#we write the names of the files in a list so we can iterate to download the files
periods=['2012-1st-quarter','2012-2nd-quarter', '2012-3rd-quarter', '2012-4th-quarter']
general=[]
#we generate a loop to read the files from the capital bikeshare website
for i in periods:
url = 'https://www.capitalbikeshare.com/assets/files/trip-history-data/'+i+'.csv'
response = urllib2.urlopen(url)
x=pd.read_csv(response)
general.append(x)
q1=pd.DataFrame(general[0])
谢谢!
【问题讨论】:
-
从技术上讲,这在您的代码中没有任何问题,尽管您可能会受益于创建一个接受
periods index或 name 之类的参数并且仅在调用时返回 Dataframe 的函数。
标签: python python-2.7 pandas dataframe