简体   繁体   English

如何使用python在带字符串参数的for循环中定义函数

[英]How to define a function in a for loop with the string parameter using python

Here is a DateFrame,like this: 这是一个DateFrame,如下所示:

    df_12=df[df.index.year==2012]

I want to get a series df_X ,X='13','14','15',like bellow 我想要一个像波纹管一样的系列df_X,X = '13','14','15'

    df_13,df_14...

In fact,I can get it directly,by doing: 实际上,我可以通过执行以下操作直接获得它:

   df_13=df[df.index.year==2013]
   df_14=df[df.index.year==2014]
   df_15=df[df.index.year==2015]
   df_16=df[df.index.year==2016]

But ,it will get crazy when the X get very large.So,I try to use a for loop, 但是,当X变得很大时,它将变得疯狂。因此,我尝试使用for循环,

  for x in ['13','14','15','16']:
      df_+x=df[df.index.year==int('20'+x)]

It raises a error,and I know why I was wrong. 它引发了一个错误,我知道为什么我错了。 Could anybody get it by using a loop? 有人可以通过循环来获得它吗? Thanks! 谢谢!

I am not an expert, but I think you coud use dictionaries, and do something like this: 我不是专家,但我认为您可以使用字典,并执行以下操作:

import numpy as np
x=range(10)

name=[0]*len(x)
for i, number in enumerate(x):
    name[i]='df_{0}'.format(x[i])

year=range(2013,2023)

data=dict(zip(name,year))

So, you can recall youd data: 因此,您可以调用您的数据:

data['df_0']
Out[45]: 2013

Actually, I don't know if you can use it with DataFrames... 实际上,我不知道您是否可以将其与DataFrames一起使用...

Your problem is that you can't have a variable variable name: df_+x on the left-hand side of an assignment. 您的问题是您不能在变量的左侧使用变量变量名称: df_+x

@mgilson is right, you should really create a list or dict of date frames. @mgilson是正确的,您应该真正创建日期框架的列表或字典。 If repeated references to df[df.index.year==2012] is too cumbersome, 如果重复引用df[df.index.year==2012]太麻烦了,

df_ = {}
for x in ['13','14','15','16']:
      df_[x]=df[df.index.year==int('20'+x)]

# usage
df_['13'] 

Integer keys would be less bother to type than string ones, ie use for x in [13,14,15,16] and df_[13] 整数键比字符串键更容易打扰,即for x in [13,14,15,16]df_[13] for x in [13,14,15,16]

If you are really absolutely determined to do something horrible, there is locals() which gives you access to the local namespace as a dict. 如果您确实有决心做些可怕的事情,可以使用locals()来访问本地名称空间作为字典。

 locals()["df_"+x] = df[df.index.year==int('20'+x)]

My advice: just don't! 我的建议:就是不要!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM