whitebear whitebear - 3 years ago 79
Python Question

Fetch column from datafrom and use as array by python pandas

I want to fetch the column from dataframe to the array.

then make new array from this array attach to original dataframe.

My DataFrame(df) is like this.

close per
0 637.0 -0.156740
1 638.0 0.789889
2 633.0 -1.555210
3 643.0 -1.832061
4 655.0 0.000000


Then I try to fetch column from DataFrame and make moving average.

newarray = pandas.rollling_mean(df.per,3) ## fetch array


then I want to attach this to original datafrom

df[sma] = newarray


What I want to get finally is like this

close per sma
0 637.0 -0.156740 636
1 638.0 0.789889 638
2 633.0 -1.555210 643.6
3 643.0 -1.832061 nan
4 655.0 0.000000 nan


However I think there is something comfusion with dataframe and array.

Maybe I might be misunderstanding.

How can I correct this??

Answer Source

depending on your goals:

In [39]: df['sma'] = df.close.rolling(3).mean()

In [40]: df
Out[40]:
   close       per         sma
0  637.0 -0.156740         NaN
1  638.0  0.789889         NaN
2  633.0 -1.555210  636.000000
3  643.0 -1.832061  638.000000
4  655.0  0.000000  643.666667

or:

In [36]: df['sma'] = df.close.rolling(3, center=True).mean().shift(-1)

In [37]: df
Out[37]:
   close       per         sma
0  637.0 -0.156740  636.000000
1  638.0  0.789889  638.000000
2  633.0 -1.555210  643.666667
3  643.0 -1.832061         NaN
4  655.0  0.000000         NaN
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download