【问题标题】:using pandas built-in functions and for statements to compute min and max values with python使用 pandas 内置函数和 for 语句用 python 计算最小值和最大值
【发布时间】:2019-08-22 23:51:24
【问题描述】:

我导入数据并将其分配给名为 life_exppandas DataFrame。这是我在 DataFrame 中读取的代码。

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

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

【问题讨论】:

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

标签: python pandas dataframe append max


【解决方案1】:

以下是实现此目的的方法:

# 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')

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2020-12-23
    • 2013-10-28
    相关资源
    最近更新 更多