Python|熊猫 dataframe.median()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas dataframe.median()
函数返回请求轴的值的中位数
如果该方法应用于 pandas 系列对象,则该方法返回一个标量值,该值是数据框中所有观察值的中值。如果该方法应用于 pandas 数据框对象,则该方法返回一个 pandas 系列对象,其中包含指定轴上的值的中值。
Syntax:DataFrame.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters :
axis : Align object with threshold along the given axis.
skipna : Exclude NA/null values when computing the result
level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series
numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : median : Series or DataFrame (if level specified)
示例 #1:使用median()
函数查找索引轴上所有观测值的中值。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[12, 4, 5, 44, 1],
"B":[5, 2, 54, 3, 2],
"C":[20, 16, 7, 3, 8],
"D":[14, 3, 17, 2, 6]})
# Print the dataframe
df
让我们使用dataframe.median()
函数在索引轴上找到中位数
# Find median Even if we do not specify axis = 0, the method
# will return the median over the index axis by default
df.median(axis = 0)
输出 :
示例 #2:在具有Na
值的数据帧上使用median()
函数。还要找到列轴上的中位数。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[12, 4, 5, None, 1],
"B":[7, 2, 54, 3, None],
"C":[20, 16, 11, 3, 8],
"D":[14, 3, None, 2, 6]})
# Print the dataframe
df
让我们实现中值函数。
# skip the Na values while finding the median
df.median(axis = 1, skipna = True)
输出 :