当前位置:   article > 正文

python 中 series常用操作_两个series合并成dataframe

两个series合并成dataframe

1. 两个series 合并 dataframe ----pd.concat()

df_concat_resample = pd.concat([nr_in_27, nr_in_103], axis=1, ignore_index=False)
  • 1

首先创建两个Series对象为例

首先要提醒的是,DataFrame对象的每一列都可以看做是一个Series对象
换句话说,DataFrame对象可以看做是多个Series对象拼接而成

在这里插入图片描述


在这里插入图片描述
concat()函数里面有两个常用的参数axis 和ignore_index, 默认值分别为axis=0, ignore_index=False, axis=0表示行拼接,axis=1表示列拼接

  1. 首先尝试直接对 s1s2 使用 pd.concat([s1, s2], axis=0, ignore_index=False),会发现这样会直接把s1和s2进行简单的行拼接————拼成一列
    在这里插入图片描述
  2. 对s1和s2使用pd.concat([s1, s2], axis=1, ignore_index=False),结果是把s1和s2中具有相同索引的值进行了拼接, 最后的结果变成了一个具有两列的DataFrame对象
    在这里插入图片描述

2. pd.Series 之间的相关运算

在这里插入图片描述

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

3.1 先运行下面的程序

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3.2 然后在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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

下面是运算交互:

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/663923
推荐阅读
相关标签
  

闽ICP备14008679号