python - 数据框+pandas+选择特定行

标签 python pandas dataframe

我是 pandas 的新手,我的一个函数没有按预期运行。我有这个数据框:

     title_year        gross
0          2009  7.60506e+08
1          2007  3.09404e+08
2          2015  2.00074e+08
3          2012  4.48131e+08
5          2012  7.30587e+07
6          2007   3.3653e+08
7          2010  2.00807e+08
8          2015  4.58992e+08
9          2009  3.01957e+08

功能是:

def analysis_gross_per_year(year1, year2):
    year_df = data[['title_year', 'gross']]
    check = True
    year_df.title_year = year_df.title_year.fillna('Not Given')
    year_df.gross = year_df.gross.fillna('Not Given')
    year_df = year_df[year_df.gross != 'Not Given']
    gross_year = year_df[year_df.title_year.str.contains(year1, na=True)]
    number = int(year1)
    while check :
        if str(number) == year2:
            check = False
        else:
            number = number + 1
            df1 = year_df[year_df.title_year.str.contains(str(number), na=False)]
            gross_year = pd.concat([gross_year, df1])
            print (df1)

我为函数提供了第 1 年和第 2 年的 2 个参数,它应该根据所提供年份的总收入显示平均值、最小值、最大值的折线图。

例如,如果 2013 年和 2015 年。它应该显示 2013 年、2014 年、2015 年的折线图。但是,当我运行 str.contains(year1, na=True) 时,它返回一个空数据框。你能告诉我为什么吗?

最佳答案

如果您的 title_year 列被转换为 int,您可以执行如下操作。

import matplotlib.pyplot as plt
%matplotlib inline

def range_plot(year1, year2, agg):
    for a in agg: # iterate through aggregate methods
        _ = df[df['title_year'].between(year1, year2)] # subset DataFrame to contain only the year ranges specified
        _ = _.groupby('title_year').agg(a) # groupby title_year, compute summary statistic
        plt.plot(_.index.values, _['gross'], label=a) # plot

    plt.legend() # display legend
    plt.xlabel('Year')
    plt.ylabel('Gross')
    plt.title("{} - {}".format(year1, year2))

year1 和year2 是整数,agg 是要绘制的聚合函数的列表。

range_plot(2009, 2015, ['mean', 'sum', 'min', 'max'])

enter image description here

关于python - 数据框+pandas+选择特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47671733/

相关文章:

python - 如何减去两个不同数据帧之间的行并替换原始值?

python - 尝试基于三个条件创建新的 id 列时出现问题?

python - Matplotlib Boxplot 和 pandas 数据框数据类型

python - 使用外键映射从使用 Python 和 SQLAlchemy 的其他表中获取数据

python - 如何使用 python 从公共(public)谷歌表中获取数据?

python - 从 pandas 数据框中的索引获取前后行

python - 根据工作表名称从多个Excel工作簿中创建数据框?

scala - 迭代数据框中的每一行,将其存储在 val 中并作为参数传递给 Spark SQL 查询

Python:使用 %x(语言环境)格式化的日期与预期不符

python - 从 Python 中的基类导入子类