【问题标题】:Python pandas: accumulate data frame rows by conditionPython pandas:按条件累积数据框行
【发布时间】:2015-02-19 18:04:51
【问题描述】:

我有一个包含 2 列的数据框,格式如下:

Anna         15
Mary         14
Elizabeth    11
Margaret     10
Alice         6
Bertha        5
Helen         5
Emily         4
Maria         4
Marie         4
Catherine     4
Marion        4
Ellen         4
Florence      4
Augusta       4
...
Juliette      1
Mara          1
Elise         1
Alfrida       1
Nourelain     1
Margaretta    1
Manca         1
Aloisia       1
Hulda         1
Clear         1
Wendla        1
Ellis         1
Lulu          1
Juliet        1
Gertrude      1

如何使用value < 5 累积行以获得类似

安娜 15 玛丽 14 伊丽莎白 11 玛格丽特 10 爱丽丝 6 伯莎 5 海伦 5 其他 50

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这是一种方法:

    # create some random data
    df =pd.DataFrame({'letter': list('qwertyuiopasdfghjklzxcvbnm'),'value': np.random.randint(1,15,26)})
    

    定义一个函数,将值

    def f(x):
        if x.value <5:
            l= 'other'
        else:
            l =x.letter
        return l
    

    将函数应用于数据框:

    df['letter'] =df.apply(f,axis=1)
    

    按新字母列分组并求和:

    df.groupby('letter').sum()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-02
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多