在对具有相同索引名称的行进行分组并忽略Nan时,仅采用DataFrame中每行的特定值的平均值?

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

如果我有一个DataFrame,我想要对具有相同索引名称的行进行分组,请说:

  a   b   c
c 2   1   -
c nan 2   -
d 4   3   -
e 5   4   -
d 6   5   -

我想合并具有相同列名的行,同时在列a和b中取其值的平均值。所以df会变成:

  a  b 
c 2  1.5 
d 5  4
e 5  4

如果我做:

averaging = df.groupby(["Index"])[['a', 'b']].mean()

(“Index”是为行设置的名称)

这是有效的,除了它不会忽略南。因此,我获得了:而不是我想要的数据帧:

  a   b
c nan 1.5
d 5   4
e 5   4
python pandas numpy dataframe
1个回答
0
投票

你可以使用meanlevel=0

pd.to_numeric(df.a,errors='coerce').mean(level=0)
Out[438]: 
c    2.0
d    5.0
e    5.0
Name: a, dtype: float64

使用replace,nan也不是NaN

df=df.replace('nan',np.nan)
© www.soinside.com 2019 - 2024. All rights reserved.