Python数据分析系列5---DataFrame数据操作

1、索引对象index

pandas的索引对象负责管理轴标签和其他元数据(比如轴名称等)。构建Series或DataFrame时,所用到的任何数组或其他序列的标签都会被转换成一个Index:

In [76]: obj = pd.Series(range(3), index=['a', 'b', 'c'])

In [77]: index = obj.index

In [78]: index
Out[78]: Index(['a', 'b', 'c'], dtype='object')

In [79]: index[1:]
Out[79]: Index(['b', 'c'], dtype='object')

Index对象是不可以赋值修改的,具有不可变性。不可变使得Index对象在多个数据结构之间安全共享。

2、Series和DataFrame中数据的基本手段

2.1 重新索引

        ①pandas对象的方法reindex:其作用是创建一个新对象,它的数据符合新的索引排序。

obj2 = obj.reindex(['a','b','c','d','e'])

        ②reinex方法的method选项:实现前项值填充:

In [95]: obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])

In [96]: obj3
Out[96]: 
0      blue
2    purple
4    yellow
dtype: object

In [97]: obj3.reindex(range(6), method='ffill')
Out[97]: 
0      blue
1      blue
2    purple
3    purple
4    yellow
5    yellow
dtype: object

        ③DataFrame中的reindex方法

        reindex可以修改(行)索引和列。只传递一个序列时,会重新索引结果的行:

重新索引行:frame2 = frame.reindex(['a', 'b', 'c', 'd'])

重新索引列:states = ['Texas', 'Utah', 'California']

                      frame.reindex(columns=states)

2.2  丢弃指定轴上的项

        丢弃某条轴上的一个或多个项很简单,只要有一个索引数组或列表即可。由于需要执行一些数据整理和集合逻辑,所以drop方法返回的是一个在指定轴上删除了指定值的新对象

In [105]: obj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])

In [106]: obj
Out[106]: 
a    0.0
b    1.0
c    2.0
d    3.0
e    4.0
dtype: float64

In [107]: new_obj = obj.drop('c')

In [108]: new_obj
Out[108]: 
a    0.0
b    1.0
d    3.0
e    4.0
dtype: float64

In [109]: obj.drop(['d', 'c'])
Out[109]: 
a    0.0
b    1.0
e    4.0
dtype: float64

        DataFrame可以删除任意轴上的索引值,用标签序列调用drop会从行标签(axis 0)删除值(默认):

In [112]: data.drop(['Colorado', 'Ohio'])
Out[112]: 
          one  two  three  four
Utah        8    9     10    11
New York   12   13     14    15

        通过传递axis=1或axis='columns'可以删除列的值:

In [113]: data.drop('two', axis=1)
Out[113]: 
          one  three  four
Ohio        0      2     3
Colorado    4      6     7
Utah        8     10    11
New York   12     14    15

In [114]: data.drop(['two', 'four'], axis='columns')
Out[114]: 
          one  three
Ohio        0      2
Colorado    4      6
Utah        8     10
New York   12     14

        可以使用inplace关键字,指定替代原来的对象而不是产生新的对象: 

In [115]: obj.drop('c', inplace=True)

In [116]: obj
Out[116]: 
a    0.0
b    1.0
d    3.0
e    4.0
dtype: float64

小心使用inplace,它会销毁所有被删除的数据。

2.3  索引、选取和过滤 

        Series索引(obj[...])的工作方式类似于NumPy数组的索引,只不过Series的索引值不只是整数。下面是几个例子:

obj = pd.Series(np.arange(4.), index=['a', 'b', 'c', 'd'])
obj['b']
obj[['b', 'a', 'd']]
obj[1]
obj[2:4]
obj[[1, 3]]
obj[obj < 2]

利用标签的切片运算与普通的Python切片运算不同,其末端是包含的: 

In [125]: obj['b':'c']
Out[125]:
b    1.0
c    2.0
dtype: float64

        DataFrame索引:用一个值或序列对DataFrame进行索引其实就是获取一个或多个列。

    data = pd.DataFrame(np.arange(16).reshape((4, 4)),
    index=['Ohio', 'Colorado', 'Utah', 'New York'],
    columns=['one', 'two', 'three', 'four'])

        选取列:
        向[ ]传递单一的元素或列表,就可选择列。
        data['two']
        data[['three', 'one']]
        选取行:
        切片或布尔型数组选取数据
        data[:2]
        data[data['three'] > 5]
        选取行的语法data[:2]十分方便。

另一种用法是通过布尔型DataFrame(比如下面这个由标量比较运算得出的)进行索引:

In [134]: data < 5
Out[134]: 
            one    two  three   four
Ohio       True   True   True   True
Colorado   True  False  False  False
Utah      False  False  False  False
New York  False  False  False  False

In [135]: data[data < 5] = 0

In [136]: data
Out[136]: 
          one  two  three  four
Ohio        0    0      0     0
Colorado    0    5      6     7
Utah        8    9     10    11
New York   12   13     14    15

2.4 用loc和iloc进行选取 

        对于DataFrame的行的标签索引,有特殊的标签运算符LOC和iloc,使用轴标签(loc)或整数索引(iloc),从DataFrame选择行和列的子集:

In [137]: data.loc['Colorado', ['two', 'three']]
Out[137]: 
two      5
three    6
Name: Colorado, dtype: int64
```

        ‘‘‘用iloc和整数进行选取’’’
```python
In [138]: data.iloc[2, [3, 0, 1]]
Out[138]: 
four    11
one      8
two      9
Name: Utah, dtype: int64

In [139]: data.iloc[2]
Out[139]: 
one       8
two       9
three    10
four     11
Name: Utah, dtype: int64

In [140]: data.iloc[[1, 2], [3, 0, 1]]
Out[140]: 
          four  one  two
Colorado     7    0    5
Utah        11    8    9

loc和iloc这两个索引函数也适用于一个标签或多个标签的切片:

data.loc[:'Utah', 'two']

data.iloc[:, :3][data.three > 5]

 Series和DataFrame的算术方法

它们每个都有一个副本,以字母r开头,它会翻转参数。因此这两个语句是等价的:

2.6  DataFrame和Series之间的运算   

        与不同维度的Numpy数组的运算相似,DataFrame和Series之间的运算遵循广播(broadcast)机制,当从arr减去arr[0],每一行都会执行这个操作:

In [176]: arr
Out[176]: 
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]])

In [177]: arr[0]
Out[177]: array([ 0.,  1.,  2.,  3.])

In [178]: arr - arr[0]
Out[178]: 
array([[ 0.,  0.,  0.,  0.],
       [ 4.,  4.,  4.,  4.],
       [ 8.,  8.,  8.,  8.]])

DataFrame和Series之间的运算差不多也是如此:

In [179]: frame = pd.DataFrame(np.arange(12.).reshape((4, 3)),
   .....:                      columns=list('bde'),
   .....:                      index=['Utah', 'Ohio', 'Texas', 'Oregon'])

In [180]: series = frame.iloc[0]

In [181]: frame
Out[181]: 
          b     d     e
Utah    0.0   1.0   2.0
Ohio    3.0   4.0   5.0
Texas   6.0   7.0   8.0
Oregon  9.0  10.0  11.0

In [182]: series
Out[182]: 
b    0.0
d    1.0
e    2.0
Name: Utah, dtype: float64

默认情况下,DataFrame和Series之间的算术运算会将Series的索引匹配到DataFrame的列,然后沿着行一直向下广播:

In [183]: frame - series
Out[183]: 
          b    d    e
Utah    0.0  0.0  0.0
Ohio    3.0  3.0  3.0
Texas   6.0  6.0  6.0
Oregon  9.0  9.0  9.0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值