Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

python - Calculate numpy.std of each pandas.DataFrame's column?

I want to get the numpy.std of each column of my pandas.DataFrame.

Here is my code:

import pandas as pd
import numpy as np

prices = pd.DataFrame([[-0.33333333, -0.25343423, -0.1666666667],
                       [+0.23432323, +0.14285714, -0.0769230769],
                       [+0.42857143, +0.07692308, +0.1818181818]])

print(pd.DataFrame(prices.std(axis=0)))

Here is my code's output:

pd.DataFrame([[ 0.39590933],
              [ 0.21234018],
              [ 0.1809432 ]])

And here is the right output (if calculate with np.std)

pd.DataFrame([[ 0.32325862],
              [ 0.17337503],
              [ 0.1477395 ]])

Why am I having such difference? How can I fix that?

NOTE: I have tried to do this way:

print(np.std(prices, axis=0))

But I had the following error:

Traceback (most recent call last):
  File "C:Users*****Documents****************.py", line 10, in <module>
    print(np.std(prices, axis=0))
  File "C:Python33libsite-packages
umpycorefromnumeric.py", line 2812, in std
    return std(axis=axis, dtype=dtype, out=out, ddof=ddof)
TypeError: std() got an unexpected keyword argument 'dtype'

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They're both right: they just differ on what the default delta degrees of freedom is. np.std uses 0, and DataFrame.std uses 1:

>>> prices.std(axis=0, ddof=0)
0    0.323259
1    0.173375
2    0.147740
dtype: float64
>>> prices.std(axis=0, ddof=1)
0    0.395909
1    0.212340
2    0.180943
dtype: float64
>>> np.std(prices.values, axis=0, ddof=0)
array([ 0.32325862,  0.17337503,  0.1477395 ])
>>> np.std(prices.values, axis=0, ddof=1)
array([ 0.39590933,  0.21234018,  0.1809432 ])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...