我想使用循环创建12个标有月份名称的数据帧。因此,我创建了一个带有月份名称的列表。但是我无法像在循环中那样插入变量。forlist_monthidf_[i]for我正在尝试执行的操作是创建一个新的数据帧,就像列表中包含的每个月一样:df_new_monthdf_new_feb = df_feb[df_feb['my_feature'] > 20]我应该遵循不同的方法吗?list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']for i in list_month: df_new_[i] = df_[i][df_[i]['my_feature'] > 20] print(i, list_month[i])我得到的错误是:Traceback (most recent call last):File"/Users/annalisa/anaconda3/lib/python3.7/site_ packages/IPython/core/interactiveshell.py", line 3325, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-50-c09b1f63eb51>", line 3, in <module> df_new_[i] = df_[i][df_[i]['my_feature'] > 20]NameError: name 'df_' is not defined
2 回答
POPMUISE
TA贡献1765条经验 获得超5个赞
这是相当黑客,但应该有效,因为我正确地理解了你:
list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
exec("df_new_{month} = df_{month}[df_{month}['my_feature'] > 20]".format(month=i))
基本上,它将创建一个字符串,外观与您在脚本中键入它并执行它的方式相同。
但也许你应该重新思考,而是将数据放入相同的DataFrame中,就像
df_feb['new'] = ...
暮色呼如
TA贡献1853条经验 获得超9个赞
在我看来,你必须首先定义变量(),然后按照你的循环。
例如至少:df_for
df_ = 0
list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
for i in list_month:
df_[i] = df_[i][df_[i]['my_feature'] > 20]
print(i, list_month[i])
添加回答
举报
0/150
提交
取消
