DataFrame Series and simple arithmetic (addition, subtraction)

First, run the following program

import numpy as np
import pandas as pd
from pandas import Series, DataFrame

# 下面两个方法都可以
# frame = DataFrame(np.arange(9).reshape(3,3), columns=list('abc'), index=['one', 'two', 'threee'])
frame = DataFrame(np.arange(9).reshape(3,3), columns=['a','b','c'], index=['one', 'two', 'threee'])
# print(frame)

series = frame['b']
# print(series)

Second, then Python Console interaction

Series frame and the following:

In[3]: frame
Out[3]: 
        a  b  c
one     0  1  2
two     3  4  5
threee  6  7  8

In[4]: series
Out[4]: 
one       1
two       4
threee    7
Name: b, dtype: int32

The following operation is interactive:

DataFrame.operate(Series, axis=0)

In[5]: frame.add(series, axis=0)
Out[5]: 
         a   b   c
one      1   2   3
two      7   8   9
threee  13  14  15

In[6]: frame.sub(series, axis=0)
Out[6]: 
        a  b  c
one    -1  0  1
two    -1  0  1
threee -1  0  1

In[7]: frame.mul(series, axis=0)
Out[7]: 
         a   b   c
one      0   1   2
two     12  16  20
threee  42  49  56

In[8]: frame.div(series, axis=0)
Out[8]: 
               a    b         c
one     0.000000  1.0  2.000000
two     0.750000  1.0  1.250000
threee  0.857143  1.0  1.142857

Here are two erroneous practice:

1, Axis wrong

In[9]: frame.add(series, axis=1)
Out[9]: 
         a   b   c  one  threee  two
one    NaN NaN NaN  NaN     NaN  NaN
two    NaN NaN NaN  NaN     NaN  NaN
threee NaN NaN NaN  NaN     NaN  NaN

2, can not use + - * /these symbols arithmetic

In[11]: frame + series
Out[11]: 
         a   b   c  one  threee  two
one    NaN NaN NaN  NaN     NaN  NaN
two    NaN NaN NaN  NaN     NaN  NaN
threee NaN NaN NaN  NaN     NaN  NaN
In[12]: frame * series
Out[12]: 
         a   b   c  one  threee  two
one    NaN NaN NaN  NaN     NaN  NaN
two    NaN NaN NaN  NaN     NaN  NaN
threee NaN NaN NaN  NaN     NaN  NaN

Reference:
addition and subtraction multiplication and division cases between Baidu and experience --DataFrame Series

Published 131 original articles · won praise 81 · views 60000 +

Guess you like

Origin blog.csdn.net/weixin_43469047/article/details/104188643