在对数据框进行分组操作时出现了错误"AttributeError: 'DataFrameGroupBy' object has no attribute"。

8

我有一个数据框 news_count,以下是它的列名,来自于 news_count.columns.values 的输出:

 [('date', '') ('EBIX UW Equity', 'NEWS_SENTIMENT_DAILY_AVG') ('Date', '')
  ('day', '') ('month', '') ('year', '')]

我需要按年份和月份进行分组,并对'NEWS_SENTIMENT_DAILY_AVG'的值进行求和。以下是我尝试过的代码,但都不起作用:

尝试1

news_count.groupby(['year','month']).NEWS_SENTIMENT_DAILY_AVG.values.sum()

'AttributeError: 'DataFrameGroupBy' object has no attribute' 

尝试2

news_count.groupby(['year','month']).iloc[:,1].values.sum()

AttributeError: Cannot access callable attribute 'iloc' of 'DataFrameGroupBy' objects, try using the 'apply' method

输入数据:

      ticker       date           EBIX UW Equity    month    year
      field             NEWS_SENTIMENT_DAILY_AVG
         0      2007-05-25                   0.3992      5       2007
         1      2007-11-06                   0.3936      11      2007 
         2      2007-11-07                   0.2039      11      2007
         3      2009-01-14                   0.2881       1      2014

2
你试过 news_count.groupby(['year','month']).NEWS_SENTIMENT_DAILY_AVG.sum() 吗? - cs95
问题在于它无法识别NEWS_SENTIMENT_DAILY_AVG列。错误信息 - AttributeError:'DataFrameGroupBy'对象没有'NEWS_SENTIMENT_DAILY_AVG'属性 - Arvinth Kumar
2
你是否正在使用多列索引? - cs95
2
重置索引适用于索引,而不是列... - cs95
2
我不确定能否做到这一点,因为我不确定我是否完全理解了您的数据框架结构,那些列看起来很糟糕。请尝试显式重新分配它们:df.columns = ['date', 'avg', 'day', 'month', 'year', ...]等等。如果您可以这样做,请更新您的数据框架,并再次尝试我的第一条评论中的建议。 - cs95
显示剩余3条评论
3个回答

1

df = df.groupby(['col1', 'col2'], as_index=False).agg({'value1':'sum', 'value2':'sum'})

news_count = news_count.groupby(['year', 'month'], as_index=False).agg({'NEWS_SENTIMENT_DAILY_AVG':'sum'})


0

感谢迄今为止的答案(我在那里发表了评论,因为我还没有让这些解决方案起作用 - 也许我没有理解某些东西)。同时,我想出了另一种方法,我仍然怀疑它不是很Pythonic。它确实完成了工作,并且对于我的目的来说不需要太长时间,但如果我能弄清楚如何调整上面建议的方法使它们起作用,那将是很棒的...非常欢迎任何想法!

这就是我得到的:

    import pandas as pd
    import math
    y = ['Alex'] * 2321 + ['Doug'] * 34123  + ['Chuck'] * 2012 + ['Bob'] * 9281 
        z = ['xyz'] * len(y)
    df = pd.DataFrame({'persons': y, 'data' : z})
    percent = 10  #CHANGE AS NEEDED

    #add a 'helper'column with random numbers
    df['rand'] = np.random.random(df.shape[0])
    df = df.sample(frac=1)  #optional:  this shuffles data, just to show order doesn't matter

    #CREATE A HELPER LIST
    helper = pd.DataFrame(df.groupby('persons')['rand'].count()).reset_index().values.tolist()
    for row in helper:
        df_temp = df[df['persons'] == row[0]][['persons','rand']]
        lim = math.ceil(len(df_temp) * percent * 0.01)
        row.append(df_temp.nlargest(lim,'rand').iloc[-1][1])

    def flag(name,num):
        for row in helper:
            if row[0] == name:
                if num >= row[2]:
                    return 'yes'
                else:
                    return 'no'
    
    df['flag'] = df.apply(lambda x: flag(x['persons'], x['rand']), axis=1)

并且要检查结果:

piv = df.pivot_table(index="persons", columns="flag", values="data", aggfunc='count', fill_value=0)
piv = piv.apivend(piv.sum().rename('Total')).assign(Total=lambda x: x.sum(1))
piv['% selected'] = 100 * piv.yes/piv.Total
print(piv)

OUTPUT:
flag        no   yes  Total  % selected
persons                                
Alex      2088   233   2321   10.038776
Bob       8352   929   9281   10.009697
Chuck     1810   202   2012   10.039761
Doug     30710  3413  34123   10.002051
Total    42960  4777  47737   10.006913

看起来可以适用于不同的%s和不同数量的人...但我认为让它更简单会更好。


0
从变量news_count_res的数据框中提取所需列,然后应用聚合函数。
news_count_res = news_count[['year','month','NEWS_SENTIMENT_DAILY_AVG']]
news_count_res.group(['year','month']).sum()

谢谢这个...但是我在 "df_sample = df.groupby("persons").sample(frac=percentage_to_flag, random_state=random_state)" 处得到了 "AttributeError: 'SeriesGroupBy' object has no attribute 'sample'"。如果我能弄清楚原因,也许它会对我有用... - P E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接