python - 如何根据循环迭代创建一个新的数据框?
问题描述
我需要创建多个数据框,它们是名为 的原始数据框的切片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)
非常感谢你!
解决方案
首先,您需要使用 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
推荐阅读
- r - Rvest - eBay 会话 submit_form 不返回
- ajax - 无法将 sorttable.js 与动态创建的表一起使用。当我尝试调用 sorttable.makeSortable() 它说 table.tBodies 未定义
- r - 是否有一个 R 函数可以给我一个组中的数据计数?
- javascript - 如何在客户端使用“文件类型”NPM 模块?
- javascript - 如何计算对象数组中的所有唯一值?
- python - 从熊猫数据框中获取字符串
- python - 如何将静态表示转换为动画?
- r - recipes::step_num2factor() 在烘焙时将最后一层保留为 NA,尽管提供了足够的级别(MWE 提供)
- flutter - 如何让 ListView 在滑动时滚动到下一个元素?
- r - 带有 2 路方差分析的 p 值的汇总表(平均值 + 标准误差)