使用内置函数和for语句使用python计算最小值和最大值

使用内置函数和for语句使用python计算最小值和最大值,python,pandas,dataframe,append,max,Python,Pandas,Dataframe,Append,Max,我导入数据并将其分配给名为life\u exp的pandas数据帧。这是我在数据帧中读取的代码 life_exp = pandas.read_csv('life_expectancy.csv') life_exp = life_exp.dropna() life_exp = life_exp.set_index('Country') 我需要使用pandas内置函数和for-语句来计算每年的最小值和最大值,并将它们分别附加到列表minu per_year和max_per_year。我该怎么做呢

我导入数据并将其分配给名为
life\u exp
pandas
数据帧。这是我在数据帧中读取的代码

life_exp = pandas.read_csv('life_expectancy.csv')
life_exp = life_exp.dropna() 
life_exp = life_exp.set_index('Country')

我需要使用
pandas
内置函数和for-语句来计算每年的最小值和最大值,并将它们分别附加到列表
minu per_year
max_per_year
。我该怎么做呢?

这里有一种方法可以实现这一点:

# Create sample data
life_exp = pd.DataFrame(data={'data': np.random.rand(100)}, 
               index=pd.date_range(start='1/1/2000', periods=100, freq='MS'))

# Group the data by year and compute the min and max
df = life_exp.groupby(life_exp.index.year).min().rename(columns={'data': 'min'})
df['max'] = life_exp.groupby(life_exp.index.year).max().values
print(df)
输出:

           min       max
2000  0.008992  0.891971
2001  0.279533  0.995257
2002  0.015490  0.846069
2003  0.122584  0.981442
2004  0.027147  0.985625
2005  0.050786  0.906058
2006  0.036598  0.987301
2007  0.020434  0.988755
2008  0.405666  0.939106
确保您的索引是日期时间索引:

life_exp.Country = pd.to_datetime(life_exp.Country)
life_exp = life_exp.set_index('Country')

请展示一些示例数据,谢谢,这两个列表是否只是为了存储信息而创建的变量?将它们存储在字典中以便知道每年对应的值不是更为谨慎吗?您所说的“我需要使用内置函数和for语句”是什么意思?这是设计限制吗?