首页 > 解决方案 > 如何根据循环迭代创建一个新的数据框?

问题描述

我需要创建多个数据框,它们是名为 的原始数据框的切片economy,但我想创建数据框来引用它们对应的月份和年份。这是我到目前为止的while循环:


month = 1
year = 2016

while year < 2018:
    while month < 13:
        start = str(year) + '-' + str(month) + '-1'
        if month == 2:
            end = str(year) + '-' + str(month) + '-29'
        elif month in (9,4,6,11):
            end = str(year) + '-' + str(month) + '-30'
        else:
            end = str(year) + '-' + str(month) + '-31'
        name = 'economy' + str(month) + '_' + str(year)
        name = economy[start:end]
        print(name)
        month += 1
    year += 1

但循环只是将每次迭代添加到名为 name 的数据框,而不是创建一个新的。我试图在循环之前为经济创建一个数据框列表,如下所示,但我不知道如何继续将其包含在循环逻辑中。

economy_list = []
for y in range(1,13):
    name = 'economy' + str(y)
    economy_list.append(name)

非常感谢你!

标签: pythondataframe

解决方案


首先,您需要使用 adictionary为您切片dataframe的 s,而不是 a list,以便您可以轻松地引用它们中的每一个。

其次,正如您从一开始就知道您将拥有多少“年”和“月”一样,for循环是比while循环更好的选择。

这样做:

economy_dict = {}
for year in range(2016, 2018):
    for month in range(1, 13):
        start = str(year) + '-' + str(month) + '-1'
        if month == 2:
            end = str(year) + '-' + str(month) + '-29'
        elif month in (9,4,6,11):
            end = str(year) + '-' + str(month) + '-30'
        else:
            end = str(year) + '-' + str(month) + '-31'
        name = 'economy' + str(month) + '_' + str(year)
        sliced = economy[start:end] #I copied from your code, but it doesn't seem right, and without sample of the data, I can't correct it if neccesary.
        print(name)
        economy_dict[name] = sliced

推荐阅读