【问题标题】:Why the statistics module only returning the name of the column, but not the median value?为什么统计模块只返回列名,而不返回中值?
【发布时间】:2020-10-20 15:16:54
【问题描述】:

alcohol file

import pandas as pd
import statistics as st

def median_1(table):
    print(table.median())
    
def median_2(table):
    print(st.median(table))

# Reading the excel file and sorting the value according to the X column
file=pd.read_excel("C:\\Users\\hp\\Desktop\\alcohol.xls").sort_values("X")

#Forming the new index using list comprehension
index_row=[i+1 for i in range(len(file))]

#making the new index compatible
index_new=pd.Index(index_row)

#Extracting the column named X and converting it into dataframe
column_df=pd.DataFrame(file.loc[:,"X"])

#setting the new index 
new=column_df.set_index(index_new)


median_1(new)
median_2(new)

Median_1 正在返回列名和中间值,但它应该只返回中间值。

median_2 函数不返回中间值,它只是返回列的名称。

Output:
runfile('C:/Users/hp/Desktop/eg.py', wdir='C:/Users/hp/Desktop')
X    562.5
dtype: float64
X

【问题讨论】:

    标签: python pandas statistics return median


    【解决方案1】:

    st.median() 将列表而不是数据框作为输入。由于new 是一个数据框,它不起作用。您可以在传递参数时指定列。

    median_2(new['X']) 
    # this will give you the median value without the column name
    562.5
    

    df.median() 同样适用于 median_1 函数。

    median_1(new['X'])
    # this will also give you the median value without the column name
    562.5
    

    【讨论】:

    • 你能建议我如何提高我的编码技能或者这段代码足够好吗?
    • @ChitranshMathur 根据我的经验,你只需要练习编码才能做得更好。尝试接受来自codingame、hackerrank等的编码挑战,这将培养你的技能。
    • 我的意思是我应该使用花哨的语法和花哨的功能吗?谢谢
    • @ChitranshMathur 对我来说,只要你实现了你的目标并不重要
    猜你喜欢
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多