熊猫集团按平均发行量

问题描述 投票:1回答:2

我试图找到每轮比赛的平均数(R1,R2,R3,R4)。不幸的是,没有进行的轮次以3种不同的方式表示(0,-或空单元格)。

    event   plyr    R1  R2  R3  R4
0   Houston Dave    67  90.0    70  72
1   Houston Bobx    69  69.0    69  69
2   Houston Carlx   69  71.0    71  71
3   Miamixx Cliff   67  70.0    70  70
4   Miamixx Dean    70  71.0    71  71
5   Miamixx Clive   69  69.0    -   0
6   Miamixx Patxx   71  70.0    -   0
7   Atlanta Phil    67  70.0    70  72
8   Atlanta Dave    69  NaN 71  73
9   Atlanta Bobx    69  NaN -   0

我试过用NaN代替0和-,但仍然得到不同的结果。

df['R3'] = df['R3'].replace(['0', '-'], np.nan)df['R4'] = df['R4'].replace(['0', '-'], np.nan)

结果

df.groupby('event')['R1','R2', 'R3', 'R4'].mean()


R1  R2  R4
event           
Atlanta 68.333333   70.000000   48.333333
Houston 68.333333   76.666667   70.666667
Miamixx 69.250000   70.000000   35.250000
python pandas group-by nan
2个回答
1
投票

groupby 均值聚合将排除 NaN 值,但包括零。所以你需要用 0 或保留 NaN 取决于你想要的结果。

这将设置所有的 -NaN 值到 0:

cols = ['R1', 'R2', 'R3', 'R4']

for col in cols:
    df[col] = np.where((df[col]=='-') | (df[col].isnull()==True), 0, df[col])
    df[col] = pd.to_numeric(df[col])

df.groupby('event').mean()

如果你想 NaN 而不是 0 只需更换 0np.where()np.NaN.


0
投票

to_csvread_csv

阅读 csv 适当 NaN 指定值则 fillna0

from io import StringIO as io_
df = pd.read_csv(io_(df.to_csv(index=False)), na_values=['-']).fillna(0)

df.groupby('event')[['R1', 'R2', 'R3', 'R4']].mean()

                R1         R2     R3         R4
event                                          
Atlanta  68.333333  23.333333  47.00  48.333333
Houston  68.333333  76.666667  70.00  70.666667
Miamixx  69.250000  70.000000  35.25  35.250000

pd.to_numeric

df.filter(like='R').apply(pd.to_numeric, errors='coerce') \
  .fillna(0).groupby(df.event).mean()

                R1         R2     R3         R4
event                                          
Atlanta  68.333333  23.333333  47.00  48.333333
Houston  68.333333  76.666667  70.00  70.666667
Miamixx  69.250000  70.000000  35.25  35.250000
© www.soinside.com 2019 - 2024. All rights reserved.