使用NumPy函数和Pandas DataFrame计算样本统计信息

时间:2018-10-08 03:23:51

标签: python pandas numpy dataframe

我正在尝试创建一个函数,该函数使用NumPy函数返回Pandas DataFrame中所有列的均值,中位数或标准差。

这是用于学校作业,因此没有其他原因使用NumPy。我正在努力解决如何将NumPy函数与Pandas DataFrame一起使用的问题。

这是问题的内容。

下面的代码单元包含一个名为comp_sample_stat的函数,该函数接受2个参数“ df”(其中包含来自特定公司的道琼斯数据)和stat(其将包含3个字符串之一):“ mean”,“ std”,或“中位数”。

针对此问题:

  • 如果stat等于“ mean”,则使用numpy的均值函数返回数据框列的均值
  • 如果统计信息等于“ median”,则使用numpy的中值函数返回数据框列的中值
  • 如果统计信息等于“ std”,则使用numpy的std函数返回数据框列的std

这是我编写的函数。

def comp_sample_stat(df, stat='mean'):
'''
Computes a sample statistic for any dataframe passed in

Parameters
----------
df: Pandas dataframe 

Returns
-------
a pandas dataframe
'''
    df_mean = df.apply(np.mean(df))
    df_median = df.apply(np.median(df))
    df_std = df.apply(np.std(df))

    if stat is str('std'):
        return df_std
    elif stat is str('median'):
        return df_median
    else:
        return df_mean

df是以前在我的任务中定义的一个DataFrame,如下所示:

def read_data(file_path):
'''
Reads in a dataset using pandas.

Parameters
----------
file_path : string containing path to a file

Returns
-------
pandas dataframe with data read in from the file path
'''
    read_file = pd.read_csv(file_path)
    new_df = pd.DataFrame(read_file)
    return new_df    

df = read_data('data/dow_jones_index.data')

变量df_AA先前也已定义如下:

def select_stock(df, symbol):
'''
Selects data only containing a particular stock symbol.

Parameters
----------
df: dataframe containing data from the dow jones index
stock: string containing the stock symbol to select

Returns
-------
dataframe containing a particular stock
'''
    stock = df[df.stock == symbol]
    return stock
df_AA = select_stock(df.copy(), 'AA')

当我按以下方式在Jupyter Notebook中调用该函数时:

comp_sample_stat(df_AA)

我收到以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call 
last)
<ipython-input-17-a2bcbeedcc56> in <module>()
 22         return df_mean
 23 
---> 24 comp_sample_stat(df_AA)

<ipython-input-17-a2bcbeedcc56> in comp_sample_stat(df, stat)
 11     a pandas dataframe
 12     '''
---> 13     df_mean = df.apply(np.mean(df))
 14     df_median = df.apply(np.median(df))
 15     df_std = df.apply(np.std(df))

/opt/conda/lib/python3.6/site-packages/pandas/core/frame.py in 
apply(self, func, axis, broadcast, raw, reduce, result_type, args, 
**kwds)
6012                          args=args,
6013                          kwds=kwds)
-> 6014         return op.get_result()
6015 
6016     def applymap(self, func):

/opt/conda/lib/python3.6/site-packages/pandas/core/apply.py in 
get_result(self)
316                                       *self.args, **self.kwds)
317 
--> 318         return super(FrameRowApply, self).get_result()
319 
320     def apply_broadcast(self):

/opt/conda/lib/python3.6/site-packages/pandas/core/apply.py in 
get_result(self)
140             return self.apply_raw()
141 
--> 142         return self.apply_standard()
143 
144     def apply_empty_result(self):

/opt/conda/lib/python3.6/site-packages/pandas/core/apply.py in 
apply_standard(self)
246 
247         # compute the result using the series generator
--> 248         self.apply_series_generator()
249 
250         # wrap results

/opt/conda/lib/python3.6/site-packages/pandas/core/apply.py in 
apply_series_generator(self)
275             try:
276                 for i, v in enumerate(series_gen):
--> 277                     results[i] = self.f(v)
278                     keys.append(v.name)
279             except Exception as e:

TypeError: ("'Series' object is not callable", 'occurred at index 
quarter')

1 个答案:

答案 0 :(得分:2)

DataFrame.apply希望您传递给它一个函数,而不是数据帧。因此,您应该传递不带参数的np.mean

也就是说,您应该这样做:

df_mean = df.apply(np.mean)

docs