74_Pandas median获取中位数

74_Pandas median获取中位数

使用median()方法获取pandas.DataFrame、pandas.Series的中值(1/2分位数、第50个百分位数)。

中位数的定义如下。

中位数:是将有限个数据按降序排列时位于中间的值。如果有偶数个数据,则取最靠近中心的两个值的算术平均值。

本节解释以下内容。

  • 中值()的基本用法
    • 当行数/元素数为偶数时
  • 指定行/列:参数axis

中值()的基本用法

以下面的 pandas.DataFrame 为例。

import pandas as pd

df = pd.DataFrame({'col_1': range(5),
                   'col_2': [i ** 2 for i in range(5)],
                   'col_3': list('abcde')})

print(df)
#    col_1  col_2 col_3
# 0      0      0     a
# 1      1      1     b
# 2      2      4     c
# 3      3      9     d
# 4      4     16     e

默认情况下,数字字符串的中值作为 pandas.Series 返回。非数字列将被忽略。

print(df.median())
# col_1    2.0
# col_2    4.0
# dtype: float64

print(type(df.median()))
# <class 'pandas.core.series.Series'>

如果从 pandas.Series 调用中值(),中值将以浮点数形式返回。

print(df['col_1'].median())
# 2.0

print(type(df['col_1'].median()))
# <class 'numpy.float64'>

当行数/元素数为偶数时

如上例所示,如果行数和元素数为奇数,则按原样返回中心值。 如果行数/元素数为偶数,则返回两个中心值的平均值。

df_even = pd.DataFrame({'col_1': range(6),
                        'col_2': [i ** 2 for i in range(6)],
                        'col_3': list('abcdef')})

print(df_even)
#    col_1  col_2 col_3
# 0      0      0     a
# 1      1      1     b
# 2      2      4     c
# 3      3      9     d
# 4      4     16     e
# 5      5     25     f

print(df_even.median())
# col_1    2.5
# col_2    6.5
# dtype: float64

指定行/列:参数axis

默认情况下,处理每一列,但如果指定参数 axis=1,则处理每一行。在这种情况下,非数字列也会被忽略。

print(df)
#    col_1  col_2 col_3
# 0      0      0     a
# 1      1      1     b
# 2      2      4     c
# 3      3      9     d
# 4      4     16     e
print(df.median(axis=1))
# 0     0.0
# 1     1.0
# 2     3.0
# 3     6.0
# 4    10.0
# dtype: float64
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值