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

Python 如何根据循环迭代创建新的数据帧?,python,dataframe,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)

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

多谢各位

首先,您需要为切片的
数据帧使用
字典
,而不是
列表
,以便您可以轻松地引用其中的每一个

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

我们也要这样做:

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

您可以共享
economy
数据帧吗?请参阅:。谢谢,解决方案非常有效!sliced=economy[start:end]之所以有效,是因为我将日期列设置为数据帧的索引(:
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