猿问

通过将元素设置为变量来循环访问列表

我想使用循环创建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


叮当猫咪
浏览 146回答 2
2回答

POPMUISE

这是相当黑客,但应该有效,因为我正确地理解了你:list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']for i in list_month:&nbsp; &nbsp; exec("df_new_{month} = df_{month}[df_{month}['my_feature'] > 20]".format(month=i))基本上,它将创建一个字符串,外观与您在脚本中键入它并执行它的方式相同。但也许你应该重新思考,而是将数据放入相同的DataFrame中,就像df_feb['new'] = ...

暮色呼如

在我看来,你必须首先定义变量(),然后按照你的循环。例如至少:df_fordf_ = 0&nbsp;list_month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']for i in list_month:&nbsp; &nbsp; df_[i] = df_[i][df_[i]['my_feature'] > 20]&nbsp; &nbsp; print(i, list_month[i])&nbsp;
随时随地看视频慕课网APP

相关分类

Python
我要回答