# apply 和 applymap

### 1. 可直接使用NumPy的函数

``````# Numpy ufunc 函数
df = pd.DataFrame(np.random.randn(5,4) - 1)
print(df)

print(np.abs(df))
``````

``````          0         1         2         3
0 -0.062413  0.844813 -1.853721 -1.980717
1 -0.539628 -1.975173 -0.856597 -2.612406
2 -1.277081 -1.088457 -0.152189  0.530325
3 -1.356578 -1.996441  0.368822 -2.211478
4 -0.562777  0.518648 -2.007223  0.059411

0         1         2         3
0  0.062413  0.844813  1.853721  1.980717
1  0.539628  1.975173  0.856597  2.612406
2  1.277081  1.088457  0.152189  0.530325
3  1.356578  1.996441  0.368822  2.211478
4  0.562777  0.518648  2.007223  0.059411
``````

### 2. 通过apply将函数应用到列或行上

``````# 使用apply应用行或列数据
#f = lambda x : x.max()
print(df.apply(lambda x : x.max()))
``````

``````0   -0.062413
1    0.844813
2    0.368822
3    0.530325
dtype: float64
``````

``````# 指定轴方向，axis=1，方向是行
print(df.apply(lambda x : x.max(), axis=1))
``````

``````0    0.844813
1   -0.539628
2    0.530325
3    0.368822
4    0.518648
dtype: float64
``````

### 3. 通过applymap将函数应用到每个数据上

``````# 使用applymap应用到每个数据
f2 = lambda x : '%.2f' % x
print(df.applymap(f2))
``````

``````       0      1      2      3
0  -0.06   0.84  -1.85  -1.98
1  -0.54  -1.98  -0.86  -2.61
2  -1.28  -1.09  -0.15   0.53
3  -1.36  -2.00   0.37  -2.21
4  -0.56   0.52  -2.01   0.06
``````

# 排序

### 1. 索引排序

`sort_index()`

`排序默认使用升序排序，ascending=False 为降序排序`

``````# Series
s4 = pd.Series(range(10, 15), index = np.random.randint(5, size=5))
print(s4)

# 索引排序
s4.sort_index() # 0 0 1 3 3
``````

``````0    10
3    11
1    12
3    13
0    14
dtype: int64

0    10
0    14
1    12
3    11
3    13
dtype: int64
``````

``````# DataFrame
df4 = pd.DataFrame(np.random.randn(3, 5),
index=np.random.randint(3, size=3),
columns=np.random.randint(5, size=5))
print(df4)

df4_isort = df4.sort_index(axis=1, ascending=False)
print(df4_isort) # 4 2 1 1 0
``````

``````          1         4         0         1         2
2 -0.416686 -0.161256  0.088802 -0.004294  1.164138
1 -0.671914  0.531256  0.303222 -0.509493 -0.342573
1  1.988321 -0.466987  2.787891 -1.105912  0.889082

4         2         1         1         0
2 -0.161256  1.164138 -0.416686 -0.004294  0.088802
1  0.531256 -0.342573 -0.671914 -0.509493  0.303222
1 -0.466987  0.889082  1.988321 -1.105912  2.787891
``````

### 2. 按值排序

`sort_values(by='column name')`

`根据某个唯一的列名进行排序，如果有其他相同列名则报错。`

``````# 按值排序
df4_vsort = df4.sort_values(by=0, ascending=False)
print(df4_vsort)
``````

``````          1         4         0         1         2
1  1.988321 -0.466987  2.787891 -1.105912  0.889082
1 -0.671914  0.531256  0.303222 -0.509493 -0.342573
2 -0.416686 -0.161256  0.088802 -0.004294  1.164138
``````

# 处理缺失数据

``````df_data = pd.DataFrame([np.random.randn(3), [1., 2., np.nan],
[np.nan, 4., np.nan], [1., 2., 3.]])
``````

``````          0         1         2
0 -0.281885 -0.786572  0.487126
1  1.000000  2.000000       NaN
2       NaN  4.000000       NaN
3  1.000000  2.000000  3.000000
``````

### 1. 判断是否存在缺失值：isnull()

``````# isnull
print(df_data.isnull())
``````

``````       0      1      2
0  False  False  False
1  False  False   True
2   True  False   True
3  False  False  False
``````

### 2. 丢弃缺失数据：dropna()

``````# dropna
print(df_data.dropna())

print(df_data.dropna(axis=1))
``````

``````          0         1         2
0 -0.281885 -0.786572  0.487126
3  1.000000  2.000000  3.000000

1
0 -0.786572
1  2.000000
2  4.000000
3  2.000000
``````

### 3. 填充缺失数据：fillna()

``````# fillna
print(df_data.fillna(-100.))
``````

``````            0         1           2
0   -0.281885 -0.786572    0.487126
1    1.000000  2.000000 -100.000000
2 -100.000000  4.000000 -100.000000
3    1.000000  2.000000    3.000000
``````

# 2.层级索引（hierarchical indexing）

``````import pandas as pd
import numpy as np

ser_obj = pd.Series(np.random.randn(12),index=[
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
])
print(ser_obj)
``````

``````a  0    0.099174
1   -0.310414
2   -0.558047
b  0    1.742445
1    1.152924
2   -0.725332
c  0   -0.150638
1    0.251660
2    0.063387
d  0    1.080605
1    0.567547
2   -0.154148
dtype: float64
``````

# MultiIndex索引对象

• 打印这个Series的索引类型，显示是MultiIndex

• 直接将索引打印出来，可以看到有lavels,和labels两个信息。lavels表示两个层级中分别有那些标签，labels是每个位置分别是什么标签。

``````print(type(ser_obj.index))
print(ser_obj.index)
``````

``````<class 'pandas.indexes.multi.MultiIndex'>
MultiIndex(levels=[['a', 'b', 'c', 'd'], [0, 1, 2]],
labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]])
``````

# 选取子集

• 根据索引获取数据。因为现在有两层索引，当通过外层索引获取数据的时候，可以直接利用外层索引的标签来获取。

• 当要通过内层索引获取数据的时候，在list中传入两个元素，前者是表示要选取的外层索引，后者表示要选取的内层索引。

### 1. 外层选取：

`ser_obj['outer_label']`

``````# 外层选取
print(ser_obj['c'])
``````

``````0   -1.362096
1    1.558091
2   -0.452313
dtype: float64
``````
1. 内层选取：

`ser_obj[:, 'inner_label']`

``````# 内层选取
print(ser_obj[:, 2])
``````

``````a    0.826662
b    0.015426
c   -0.452313
d   -0.051063
dtype: float64
``````

# 交换分层顺序

### 1. swaplevel()

`.swaplevel( )交换内层与外层索引。`

``````print(ser_obj.swaplevel())
``````

``````0  a    0.099174
1  a   -0.310414
2  a   -0.558047
0  b    1.742445
1  b    1.152924
2  b   -0.725332
0  c   -0.150638
1  c    0.251660
2  c    0.063387
0  d    1.080605
1  d    0.567547
2  d   -0.154148
dtype: float64
``````

# 交换并排序分层 sortlevel()

• .sortlevel( )先对外层索引进行排序，再对内层索引进行排序，默认是升序。

``````# 交换并排序分层
print(ser_obj.swaplevel().sortlevel())
``````

``````0  a    0.099174
b    1.742445
c   -0.150638
d    1.080605
1  a   -0.310414
b    1.152924
c    0.251660
d    0.567547
2  a   -0.558047
b   -0.725332
c    0.063387
d   -0.154148
dtype: float64
``````

# 3.Pandas统计计算和描述

``````import numpy as np
import pandas as pd

df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj)
``````

``````          a         b         c         d
0  1.469682  1.948965  1.373124 -0.564129
1 -1.466670 -0.494591  0.467787 -2.007771
2  1.368750  0.532142  0.487862 -1.130825
3 -0.758540 -0.479684  1.239135  1.073077
4 -0.007470  0.997034  2.669219  0.742070
``````

### 常用的统计计算

`sum`, `mean`, `max`, `min`

axis=0 按列统计，axis=1按行统计

skipna 排除缺失值， 默认为True

``````df_obj.sum()

df_obj.max()

df_obj.min(axis=1, skipna=False)
``````

``````a    0.605751
b    2.503866
c    6.237127
d   -1.887578
dtype: float64

a    1.469682
b    1.948965
c    2.669219
d    1.073077
dtype: float64

0   -0.564129
1   -2.007771
2   -1.130825
3   -0.758540
4   -0.007470
dtype: float64
``````

## describe 产生多个统计数据

``````print(df_obj.describe())
``````

``````              a         b         c         d
count  5.000000  5.000000  5.000000  5.000000
mean   0.180305  0.106488  0.244978  0.178046
std    0.641945  0.454340  1.064356  1.144416
min   -0.677175 -0.490278 -1.164928 -1.574556
25%   -0.064069 -0.182920 -0.464013 -0.089962
50%    0.231722  0.127846  0.355859  0.190482
75%    0.318854  0.463377  1.169750  0.983663
max    1.092195  0.614413  1.328220  1.380601
``````