将平均行添加到包含“-”的数据框
adding average row to dataframe that include "-"
我将 np.nan 值转换为“-”,我想将平均行添加到我的新数据框中,但我没有得到平均输出。
date col1 col2 col3
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
我想要的输出:
date col1 col2 col3
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
Avrg. 3.5 3.3 3.25
可以这样做吗?
使用DataFrame.mask
with convert values to floats
and mean
and add to last row with DataFrame.loc
:
#if not DatetimeIndex
#df = df.set_index('date')
df.loc['Avrg.'] = df.mask(df == '-').astype(float).mean()
print (df)
col1 col2 col3
date
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
Avrg. 3.5 3.33333 3.25
我将 np.nan 值转换为“-”,我想将平均行添加到我的新数据框中,但我没有得到平均输出。
date col1 col2 col3
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
我想要的输出:
date col1 col2 col3
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
Avrg. 3.5 3.3 3.25
可以这样做吗?
使用DataFrame.mask
with convert values to floats
and mean
and add to last row with DataFrame.loc
:
#if not DatetimeIndex
#df = df.set_index('date')
df.loc['Avrg.'] = df.mask(df == '-').astype(float).mean()
print (df)
col1 col2 col3
date
2019-10-10 5 2 4
2019-10-11 - 3 0
2019-10-12 7 - -
2019-10-13 0 5 6
2019-10-14 2 - 3
Avrg. 3.5 3.33333 3.25