获取数据框架的函数源代码;计算平均值、中位数和众数。

2024-06-16 11:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

试图从数据帧中得出平均值、中位数和模式。我需要知道如何在函数中编写源代码,而不是“:”。你知道吗

source = [df.'DMC]

import pandas as pd
import nltk

df.head(4)
# This is the print out of the dataframe 
# When I came up with this code, the source was
# source=[3,4,6,4,7,2,6,7,...]
# But now I need to get the data from a dataFrame. 
#   X   Y   month   day   DMC    RH
# 0 7   5   3       fri   26.2   94.3
# 1 7   4   10      tue   90.6   35.4
# 2 6   6   12      mon   56.8   99.2
# this is just a sample

#This is the code to find the mean median and mode

source = [df:'DMC']  #This is were I need your help.
def meanmedianmode (source):
    mmm = {'mean': Mean(source), 'median': Median(source), 'mode':
            Mode(source) }
def Mean (source):
    mean = reduce(lambda x,y: x+y, numbers)/len(source)
    return mean

def Median(source):
    median = numpy.median(source)
    return(median)

def Mode (source):
    mode = statistics.mode(source)
    return mode
    return mmm
print("mean median mode" + str(meanmedianmode(source)))

Tags: theimportsourcedfreturnismodedef
1条回答
网友
1楼 · 发布于 2024-06-16 11:39:34

为了回答您的特定问题,为了选择pandas数据帧的特定列,您可以使用以下语法

source = df.DMC 

或者

source = df['DMC']

然而,你不必费心去实现你自己的函数来寻找均值,中位数和模式。谢天谢地,pandas已经包含了这三个函数。检查pandas文档下的computations/descriptive stats。 解决办法很简单

In [6]: df = pd.DataFrame({'X':[7,7,6], 'DMC':[26.2, 90.6, 56.8]})

In [7]: df
Out[7]:
    DMC  X
0  26.2  7
1  90.6  7
2  56.8  6

In [8]: df.DMC.mean()
Out[8]: 57.86666666666667

In [9]: df.DMC.median()
Out[9]: 56.8

In [10]: df.DMC.mode()
Out[10]:
0    26.2
1    56.8
2    90.6
dtype: float64

相关问题 更多 >