pandas-1:Series && DataFrame

这篇博客介绍了pandas库中的两种核心数据结构——Series和DataFrame。Series是一维带标签的数组,可以包含不同类型的元素,可通过标签或索引获取值。DataFrame是二维结构,能容纳多个Series,其表头由标签构成。博客详细讨论了这两个数据结构的创建、操作、数学运算以及数据的插入和删除。
摘要由CSDN通过智能技术生成

摘要:

  1. 两种基本的数据结构 Series 和 DataFrame

介绍

参考网址: http://pandas.pydata.org/pandas-docs/stable/

两个基本的重要的数据结构

  1. Series
  2. DataFrame

Series

>>> import pandas as pd

Series 是一个一维带标签的数组,其中你能包含任意类型的数据。Series 是一个类,其构造函数如下:

>>> help(pd.Series.__init__)
Help on method __init__ in module pandas.core.series:

__init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) unbound pandas.core.series.Series method

在创建 Series 对象的时候,一般需要提供数据,即 data,例如:

>>> ser = pd.Series(data = [100,200,300,400,500])
>>> ser
0    100
1    200
2    300
3    400
4    500
dtype: int64

也可以给数据加上标签:

>>> ser = pd.Series(data=[100,200,300,400,500], index=['tom','bob','nancy','dan','eric'])
>>> ser
tom      100
bob      200
nancy    300
dan      400
eric     500
dtype: int64

可以看到,当我们不给数据添加标签的时候,标签就自动的从零开始,直到 len(data)-1

上面的两个例子中,给出的 data 所有的元素都是同一个类型,即 int64,但其实它可以包含不同的类型,如下所示:

>>> ser = pd.Series(data=[100,'foo',300,'bar',500], index=['tom','bob','nancy','dan','eric'])
>>> ser
tom      100
bob      foo
nancy    300
dan      bar
eric     500
dtype: object

除了上面使用普通的列表作为 data 的值外, 还可以使用, narry 字典 数(scale)来对其进行赋值。

获取标签对应的值

可以通过标签获得所对应的值:

>>> ser['nancy']
300

也可以使用 loc 方法来通过标签获取值,loc 即 location:

>>> ser.loc['nancy']
300

>>> ser.loc[['nancy','dan']]
nancy    300
bob      foo
dtype: object

同样可以使用数字标签获取相应位置的值,因为默认的标签是从零开始的数字:

>>> ser[2]
300

>>> ser[[2,3]]
nancy    300
dan      bar
dtype: object

loc 方法貌似并不能使用数字标签,可以使用 iloc 方法代替之,即 index location:

>>> ser.iloc[2]
300
>>> ser.iloc[[2,3]]
nancy    300
dan      bar
dtype: object

index 属性

>>> ser.index
Index([u'tom', u'bob', u'nancy', u'dan', u'eric'], dtype='object')

使用 in 检测是否包含某个标签

>>> 'bob' in ser
True

操作符作用在 Series

>>> ser
tom      100
bob      foo
nancy    300
dan      bar
eric     500
dtype: object

>>> ser * 2
tom         200
bob      foofoo
nancy       600
dan      barbar
eric       1000
dtype: object

>>> ser[['nancy','eric']]**2
nancy     90000
eric     250000
dtype: object

其他方法

由于 Series 赋值的多样性, Series 对象可以当做一个 narry 来处理,还也可以作为 字典来处理。

具体的操作可以参见官网:http://pandas.pydata.org/pandas-docs/stable/dsintro.html#intro-to-data-structures

DataFrame

DataFrame 是 Series 的容器,可以用来包含 Series 对象。它是一个二维的数据结构。

>>> d = { 'one': pd.Series([100.,200.,300.], index=['apple','ball','clock']),
      'two': pd.Series([111.,222.,333.,444.],['apple','ball','ceril','dancy'])}
>>> df = pd.DataFrame(d)
>>> df
         one    two
apple  100.0  111.0
ball   200.0  222.0
ceril    NaN  333.0
clock  300.0    NaN
dancy    NaN  444.0

可以看到两个 Series 被融合为一个 DataFrame 对象。 标签作为表格的横向表头,字典的 keys 作为表格的 竖向表头。 标签取的是两个 Series 标签的并集,对于不包含某个标签的 Series,其值为 NaN。

同时我们可以使用部分数据来初始化 DataFrame 对象:

>>> pd.DataFrame(d, index=['dancy','apple','ball'])
         one    two
dancy    NaN  444.0
apple  100.0  111.0
ball   200.0  222.0

我们还可以使用不存在的竖表头:

>>> pd.DataFrame(d, index=['dancy','apple','ball'], columns=['one','three'])
         one three
dancy    NaN   NaN
apple  100.0   NaN
ball   200.0   NaN

获取 DataFrame 的表头

>>> df.index
Index([u'apple', u'ball', u'ceril', u'clock', u'dancy'], dtype='object')
>>> df.columns
Index([u'one', u'two'], dtype='object')

使用普通字典初始化 DataFrame

上面的初始化例子都是使用了 Series 作为值去初始化一个 DataFrame 对象。我们可以使用 python 中普通的字典数据类型去初始化。

>>> data = [{'alex':1,'joe':2},{'ema':5,'dora':10,'alice':20}]
>>> data
[{'alex': 1, 'joe': 2}, {'dora': 10, 'ema': 5, 'alice': 20}]
>>> pd.DataFrame(data)
   alex  alice  dora  ema  joe
0   1.0    NaN   NaN  NaN  2.0
1   NaN   20.0  10.0  5.0  NaN

>>> pd.DataFrame(data,index=['orange','red'])
        alex  alice  dora  ema  joe
orange   1.0    NaN   NaN  NaN  2.0
red      NaN   20.0  10.0  5.0  NaN

>>> pd.DataFrame(data,index=['orange','red'], columns=['alex','dora','alice'])
        alex  dora  alice
orange   1.0   NaN    NaN
red      NaN  10.0   20.0

我们可以看到,在初始化的时候,通过 index 参数可以设置行表头的名字,而通过 columns 可以挑选我们想要的列表头。

DataFrame 数学操作

>>> df
         one    two
apple  100.0  111.0
ball   200.0  222.0
ceril    NaN  333.0
clock  300.0    NaN
dancy    NaN  444.0

>>> df['one']
apple    100.0
ball     200.0
ceril      NaN
clock    300.0
dancy      NaN
Name: one, dtype: float64

>>> df['one']['ball']
200.0

>>> df['three'] = df['one'] + df['two']
>>> df
         one    two  three
apple  100.0  111.0  211.0
ball   200.0  222.0  422.0
ceril    NaN  333.0    NaN
clock  300.0    NaN    NaN
dancy    NaN  444.0    NaN

>>> df['flag'] = df['one'] < 300
         one    two  three   flag
apple  100.0  111.0  211.0   True
ball   200.0  222.0  422.0   True
ceril    NaN  333.0    NaN  False
clock  300.0    NaN    NaN  False
dancy    NaN  444.0    NaN  False

DataFrame 删除数据

>>> df
         one    two  three   flag
apple  100.0  111.0  211.0   True
ball   200.0  222.0  422.0   True
ceril    NaN  333.0    NaN  False
clock  300.0    NaN    NaN  False
dancy    NaN  444.0    NaN  False
>>> three = df.pop('three')
>>> three
apple    211.0
ball     422.0
ceril      NaN
clock      NaN
dancy      NaN
Name: three, dtype: float64
>>> df
         one    two   flag
apple  100.0  111.0   True
ball   200.0  222.0   True
ceril    NaN  333.0  False
clock  300.0    NaN  False
dancy    NaN  444.0  False

>>> del df['two']
>>> df
         one   flag
apple  100.0   True
ball   200.0   True
ceril    NaN  False
clock  300.0  False
dancy    NaN  False

这个过程就和列表是一样的, pop 是将该数据弹出并返回, del 时间该数据直接删除,没有返回值。

DataFrame 插入数据

>>> help(df.insert)
Help on method insert in module pandas.core.frame:

insert(self, loc, column, value, allow_duplicates=False) method of pandas.core.frame.DataFrame instance
    Insert column into DataFrame at specified location.

    If `allow_duplicates` is False, raises Exception if column
    is already contained in the DataFrame.

    Parameters
    ----------
    loc : int
        Must have 0 <= loc <= len(columns)
    column : object
    value : scalar, Series, or array-like

使用 insert 方法插入数据,第一个参数 loc 代表了我们要插入第几列。从零开始算起,如果要插入到第三列,则 loc = 2。 第二个参数 column 表示我们要插入的列的名称。 value 则是插入的数据。

>>> df
         one   flag
apple  100.0   True
ball   200.0   True
ceril    NaN  False
clock  300.0  False
dancy    NaN  False
>>> df.insert(2,'copy_of_one', df['one'])
>>> df
         one   flag  copy_of_one
apple  100.0   True        100.0
ball   200.0   True        200.0
ceril    NaN  False          NaN
clock  300.0  False        300.0
dancy    NaN  False          NaN 

>>> df.insert(3,'scale', 12)
>>> df
         one   flag  copy_of_one  scale
apple  100.0   True        100.0     12
ball   200.0   True        200.0     12
ceril    NaN  False          NaN     12
clock  300.0  False        300.0     12
dancy    NaN  False          NaN     12
>>> df.insert(4,'array',[1,2,3,4,5])
>>> df
         one   flag  copy_of_one  scale  array
apple  100.0   True        100.0     12      1
ball   200.0   True        200.0     12      2
ceril    NaN  False          NaN     12      3
clock  300.0  False        300.0     12      4
dancy    NaN  False          NaN     12      5

>>> df.insert(5,'Series',df['one'][:2])
>>> df
         one   flag  copy_of_one  scale  array  Series
apple  100.0   True        100.0     12      1   100.0
ball   200.0   True        200.0     12      2   200.0
ceril    NaN  False          NaN     12      3     NaN
clock  300.0  False        300.0     12      4     NaN
dancy    NaN  False          NaN     12      5     NaN

可以看到,value 参数可以是一个数,这样的话,所有的行都是这个数;可以是一个列表,但是列表的长度必须和表格的行数相等;也可以是一个 Series 对象,其中包含的元素数可以不等于表格的行数,不足的地方使用 NaN 补充。

我的个人博客

http://www.wangs0622.com

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值