python - 生成多个 Pandas 数据框

标签 python python-2.7 pandas dataframe

我正在从一个网站检索多个 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])

谢谢!

最佳答案

如果你使用字典会更好,也可以直接将 url 传递给 pandas.read_csv。所以简化的代码看起来像这样:

import pandas as pd

periods = ['2012-1st-quarter','2012-2nd-quarter', '2012-3rd-quarter', '2012-4th-quarter']
url = 'https://www.capitalbikeshare.com/assets/files/trip-history-data/{}.csv'
d = {period: pd.read_csv(url.format(period)) for period in periods}

然后你可以像这样访问一个特定的DataFrame:

 d['2012-4th-quarter']

遍历所有Dataframes:

for period, df in d.items():
    print period
    print df

关于python - 生成多个 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143573/

相关文章:

python - 在BeautifulSoup4,Python3中,如何停止在找到的标签内递归?

python - apache2、mod_wsgi、python 网络应用程序(bottle 框架)

python - 如何模拟点击 "Next"直到结束?

python - 跳过循环中的多次迭代

python - 在 Red Hat 6.6 版的 python2.7 中导入 Tensorflow 时出错。 'GLIBC_2.17 not found'

python pandas 以优雅的方式按条件进行行替换

python - Python中声明实例变量的两种方式?

python - 如何计算 pandas 工作日的使用情况

Python - 将数据帧切片为几个较小的数据帧

python - 按给定的时间增量查找数据帧列中的时间戳