DataFrame和Series的简单运算(加减乘除)

一、先运行下面的程序

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)

二、然后在Python Console交互

frame和Series如下:

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

下面是运算交互:

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

下面有两个错误做法:

1、axis写错

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、不能用+ - * /这些符号运算

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

参考:
百度经验——DataFrame和Series之间的加减乘除运算案例

发布了131 篇原创文章 · 获赞 81 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43469047/article/details/104188643
今日推荐