pandas 如何创建一个动态值的多个变量?

zd287kbt  于 2023-03-11  发布在  其他
关注(0)|答案(1)|浏览(135)

我想创建aprox 20图表从1989年到2021年,过滤他们im使用Pandas

year1989 = ven_df['Year'] == '1989'

所以对于变量,我可以将其用作“掩码

ven_df[year1989]

并输出一个 Dataframe ,其中包含1989年的所有值
问题是,他们是这么多年来,我发现非常无用的写同样的代码30次,甚至更多。
我想用一个循环或者一个函数来创建所有的变量:1989年到2021年,值为ven_df [“年”] ==“1989”到ven_df [“年”] ==“2021”。
我的方法是正确的吗?或者有更好的方法,我是Pandas新手,谢谢!

year1989 = ven_df['Year'] == '1989'
year1990 = ven_df['Year'] == '1990'
year1991 = ven_df['Year'] == '1991'
year1992 = ven_df['Year'] == '1992'
year1993 = ven_df['Year'] == '1993'
year1994 = ven_df['Year'] == '1994'
year1995 = ven_df['Year'] == '1995'
year1996 = ven_df['Year'] == '1996'
year1997 = ven_df['Year'] == '1997'
year1998 = ven_df['Year'] == '1998'
year1999 = ven_df['Year'] == '1999'
year2000 = ven_df['Year'] == '2000'
year2001 = ven_df['Year'] == '2001'
year2002 = ven_df['Year'] == '2002'
year2003 = ven_df['Year'] == '2003'
year2000 = ven_df['Year'] == '2004'
year2001 = ven_df['Year'] == '2005'
year2002 = ven_df['Year'] == '2006'
year2003 = ven_df['Year'] == '2007'

等等!我肯定这不是正确的做事方式...

7rfyedvj

7rfyedvj1#

masks = {}
for year in range(1989, 2022):
    masks[str(year)] = ven_df['Year'] == str(year)

访问:

ven_df[masks['1995']]

相关问题