簡體   English   中英

Python如何從單個列計算多個平均值,根據另一列中的值選擇要平均的行

[英]Python How to compute multiple averages from a single column, selecting the rows to average based on values in another column

[編輯:底部重寫的問題]

我試圖弄清楚如何計算“部分列”平均值和計數而不是使用所有值。 在偽SQL中,我想要SELECT所有值WHERE id = 10 ,然后= 20等。我假設有一個pythonic(pandastic?)方式來做這個而不使用for循環。

示例: df有3列和數千行: caseidvalue 大小寫是唯一的,id可以重復,value是數字。

case    id  value
1       10  100
2       10  500
3       20  200
4       20  150
5       20  125

我想計算值並計算每個id的值的平均值,並將它們放在新列中。

case    id  value   n_vals  av_val
1       10  100     2       300
2       10  500
3       20  300     3       200
4       20  150
5       20  150

然后刪除casevalue並為每個id保留一行(現在是唯一的):

id  n_vals  av_val
10  2       300
20  3       200

我知道如何找到len和整個列的mean ,但不知道如何為這樣的部分列做到這一點。


[REWRITEN QUESTION]:

我在7個變量中有一個20000265的df df。 case是唯一的, Id可以重復:

case        Id      title           n_words n_chars rating  rating2
20000260    131258  The Pirates     2       11      2.5     2.5
20000261    131258  The Pirates     2       11      3.5     3.5
20000262    131258  The Pirates     2       11      4.5     4.5
20000263    131260  Rentun Ruusu    2       12      3       3
20000264    131260  Rentun Ruusu    2       12      5       5
20000265    131262  Innocence       1       9       4       4

我想計算每個Id的評分數和平均評分。 這些值作為n_ratingsav_rating添加到df中,替換為每個Id在單行上聚合的ratingrating2 我想保留所有其他列,產生這樣的東西:

case        Id      title           n_words n_chars n_ratings   av_rating
20000260    131258  The Pirates     2       11      3           3.5
20000263    131260  Rentun Ruusu    2       12      2           4
20000265    131262  Innocence       1       9       1           4

基於@ U9_Forward的答案,我試過這個:

df = 
    (df.
        groupby('Id', as_index = False).
        agg({'rating':'count', 'rating2':'mean'}).
        # rename(columns = {'rating':'n_ratings', 'rating2':'av_rating'}))
        rename(columns = {'Id':'Id', 'title':'title',
                      'num_words':'num_words', 'num_chars':'num_chars',
                      'rating':'n_ratings', 'rating2':'av_rating'}, axis=1))

但是,這只保留了groupby().agg()管道中使用的3列( Idn_ratingsav_rating ),例如:

0   1   49695       3.921240
1   2   22243       3.211977
2   3   12735       3.151040

我嘗試在rename() dict中包含所有col名稱,但得到了相同的結果。

兩個問題:

  1. 是否有agg()的參數或其他方法來實現所需的結果?
  2. 我在Jupyter中獲得了一個FutureWarning,並且已經讀過使用帶有rename()的字典已被棄用或很快就會被刪除。 重命名cols的新首選方法是什么?

只需使用groupby with agg rename

print(df.groupby('id',as_index=False).agg({'case':'count','value':'mean'}).rename({'case':'n_vals','value':'av_val'},axis=1))

輸出是:

   id  n_vals  av_val
0  10       2     300
1  20       3     200

編輯:

df[['n_ratings','av_rating']]=df[['Id','title']].join(df.groupby(['Id','title']).agg({'rating':'count','rating2':'mean'}), on=['Id','title'])[['rating','rating2']]
print(df.drop_duplicates(keep='last',subset='Id'))
import pandas as pd
df = pd.DataFrame.from_dict({'case': [1,2,3,4,6],
                             'id': [10,10,20,20,20],
                             'value':[100,500,300,150,150],
                             })

df['n_vals'] = df.groupby(['id'])['id'].transform('count')
df['av_val'] = df.groupby(['id'])['value'].transform('mean')

print (df)
#   case  id  value  n_vals  av_val
#0     1  10    100       2   300.0
#1     2  10    500       2   300.0
#2     3  20    300       3   200.0
#3     4  20    150       3   200.0
#4     6  20    150       3   200.0

通過這種方式,您可以保留每一行並查看其n_valsav_val而不是使用通常的groupby agg函數丟失數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM