data : 创建透视表的dataframe
values : 要聚合的值, optional
index : 要聚合的index
columns : 要聚合的columns
aggfunc :聚合的方式, default numpy.mean
fill_value : 用来替换透视表的缺失值scalar, default None
margins : 添加所有行,列,例如在后面加个“总和”boolean, default False
dropna : 不要包含条目都是NaN的列boolean, default True
margins_name : 在边距为True时将包含总计的行/列的名称。string, default ‘All’
# 读取flights数据集
flights = pd.read_csv('data/flights.csv')
flights
MONTH | DAY | WEEKDAY | AIRLINE | ORG_AIR | DEST_AIR | SCHED_DEP | DEP_DELAY | AIR_TIME | DIST | SCHED_ARR | ARR_DELAY | DIVERTED | CANCELLED | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 1 | 4 | WN | LAX | SLC | 1625 | 58.0 | 94.0 | 590 | 1905 | 65.0 | 0 | 0 |
1 | 1 | 1 | 4 | UA | DEN | IAD | 823 | 7.0 | 154.0 | 1452 | 1333 | -13.0 | 0 | 0 |
2 | 1 | 1 | 4 | MQ | DFW | VPS | 1305 | 36.0 | 85.0 | 641 | 1453 | 35.0 | 0 | 0 |
3 | 1 | 1 | 4 | AA | DFW | DCA | 1555 | 7.0 | 126.0 | 1192 | 1935 | -7.0 | 0 | 0 |
4 | 1 | 1 | 4 | WN | LAX | MCI | 1720 | 48.0 | 166.0 | 1363 | 2225 | 39.0 | 0 | 0 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
58487 | 12 | 31 | 4 | AA | SFO | DFW | 515 | 5.0 | 166.0 | 1464 | 1045 | -19.0 | 0 | 0 |
58488 | 12 | 31 | 4 | F9 | LAS | SFO | 1910 | 13.0 | 71.0 | 414 | 2050 | 4.0 | 0 | 0 |
58489 | 12 | 31 | 4 | OO | SFO | SBA | 1846 | -6.0 | 46.0 | 262 | 1956 | -5.0 | 0 | 0 |
58490 | 12 | 31 | 4 | WN | MSP | ATL | 525 | 39.0 | 124.0 | 907 | 855 | 34.0 | 0 | 0 |
58491 | 12 | 31 | 4 | OO | SFO | BOI | 859 | 5.0 | 73.0 | 522 | 1146 | -1.0 | 0 | 0 |
58492 rows × 14 columns
# 用pivot_table方法求出每条航线每个始发地的被取消的航班总数
fp = flights.pivot_table(index='AIRLINE',columns='ORG_AIR',values='CANCELLED',
aggfunc='sum', fill_value=0).round(2)
fp.head()
ORG_AIR | ATL | DEN | DFW | IAH | LAS | LAX | MSP | ORD | PHX | SFO |
---|---|---|---|---|---|---|---|---|---|---|
AIRLINE | ||||||||||
AA | 3 | 4 | 86 | 3 | 3 | 11 | 3 | 35 | 4 | 2 |
AS | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
B6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
DL | 28 | 1 | 0 | 0 | 1 | 1 | 4 | 0 | 1 | 2 |
EV | 18 | 6 | 27 | 36 | 0 | 0 | 6 | 53 | 0 | 0 |