如何根据循环迭代创建新的数据帧?

时间:2019-11-17 01:51:29

标签: python dataframe

我需要创建多个数据帧,这些数据帧是名为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)

非常感谢您!

1 个答案:

答案 0 :(得分:0)

首先,您需要为切片的dictionary使用dataframe,而不是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