结果的差异df平均值()和df['column'].mean()

2024-05-20 01:06:29 发布

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

我只运行以下三条线路:

df = pd.read_hdf('data.h5')
print(df.mean())
print(df['derived_3'].mean())

第一个print列出了每个列的所有单独的平均值,其中一个是

^{pr2}$

第二个print只给出这个列的平均值,并给出结果

-0.504715

尽管使用科学记数法和不使用科学记数法有区别,但这些值是不同的——为什么会这样?在


使用其他方法的示例

sum()执行相同的操作会导致以下结果:

derived_3        -7.878262e+05

-788004.0

同样,结果略有不同,但是count()返回相同的结果:

derived_3         1561285

1561285

{cd5>的结果:

   id  timestamp  derived_0  derived_1  derived_2  derived_3  derived_4  \
0  10          0   0.370326  -0.006316   0.222831  -0.213030   0.729277   
1  11          0   0.014765  -0.038064  -0.017425   0.320652  -0.034134   
2  12          0  -0.010622  -0.050577   3.379575  -0.157525  -0.068550   
3  25          0        NaN        NaN        NaN        NaN        NaN   
4  26          0   0.176693  -0.025284  -0.057680   0.015100   0.180894   

   fundamental_0  fundamental_1  fundamental_2    ...     technical_36  \
0      -0.335633       0.113292       1.621238    ...         0.775208   
1       0.004413       0.114285      -0.210185    ...         0.025590   
2      -0.155937       1.219439      -0.764516    ...         0.151881   
3       0.178495            NaN      -0.007262    ...         1.035936   
4       0.139445      -0.125687      -0.018707    ...         0.630232   

   technical_37  technical_38  technical_39  technical_40  technical_41  \
0           NaN           NaN           NaN     -0.414776           NaN   
1           NaN           NaN           NaN     -0.273607           NaN   
2           NaN           NaN           NaN     -0.175710           NaN   
3           NaN           NaN           NaN     -0.211506           NaN   
4           NaN           NaN           NaN     -0.001957           NaN   

   technical_42  technical_43  technical_44         y  
0           NaN          -2.0           NaN -0.011753  
1           NaN          -2.0           NaN -0.001240  
2           NaN          -2.0           NaN -0.020940  
3           NaN          -2.0           NaN -0.015959  
4           NaN           0.0           NaN -0.007338  

Tags: dfreaddata科学nanmean线路平均值
1条回答
网友
1楼 · 发布于 2024-05-20 01:06:29

pd.DataFrame方法与pd.Series方法

df.mean()中,meanpd.DataFrame.mean,并作为独立的pd.Series对所有列进行操作。返回的是一个pd.Series,其中df.columns是新索引,每列的平均值是值。在您的初始示例中,df只有一列,因此结果是一个长度为1的系列,其中索引是该列的名称,值是该列的平均值。在

df['derived_3'].mean()中,meanpd.Series.meandf['derived_3']pd.Seriespd.Series.mean的结果将是标量。在


显示差异

显示的区别是因为df.mean的结果是pd.Series,而浮动格式由pandas控制。另一方面,df['derived_3'].mean()是python原语,不受pandas控制。在

import numpy as np
import pandas as pd

标量

^{pr2}$

pd.Series

pd.Series(np.pi)

0    3.141593
dtype: float64

使用不同的格式

with pd.option_context('display.float_format', '{:0.15f}'.format):
    print(pd.Series(np.pi))

0   3.141592653589793
dtype: float64

减少
把这些不同的方法看作是降维还是不降维是有用的。或者同义,聚合或转换。在

  • 减少a pd.DataFrame会导致pd.Series
  • 减少pd.Series会产生标量

减少

  • mean
  • sum
  • std

相关问题 更多 >