pandas DataFrame(2)-行列索引及值的获取
pandas DataFrame是二维的,所以,它既有列索引,又有行索引
上一篇里只介绍了列索引:
import pandas as pd df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) print df # 结果: A B 0 0 3 1 1 4 2 2 5
行索引自动生成了 0,1,2
如果要自己指定行索引和列索引,可以使用 index 和 column 参数:
这个数据是5个车站10天内的客流数据:
ridership_df = pd.DataFrame( data=[[ 0, 0, 2, 5, 0], [1478, 3877, 3674, 2328, 2539], [1613, 4088, 3991, 6461, 2691], [1560, 3392, 3826, 4787, 2613], [1608, 4802, 3932, 4477, 2705], [1576, 3933, 3909, 4979, 2685], [ 95, 229, 255, 496, 201], [ 2, 0, 1, 27, 0], [1438, 3785, 3589, 4174, 2215], [1342, 4043, 4009, 4665, 3033]], index=['05-01-11', '05-02-11', '05-03-11', '05-04-11', '05-05-11', '05-06-11', '05-07-11', '05-08-11', '05-09-11', '05-10-11'], columns=['R003', 'R004', 'R005', 'R006', 'R007'] )
data 参数为一个numpy二维数组, index 参数为行索引, column 参数为列索引
生成的数据以表格形式显示:
R003 R004 R005 R006 R007 05-01-11 0 0 2 5 0 05-02-11 1478 3877 3674 2328 2539 05-03-11 1613 4088 3991 6461 2691 05-04-11 1560 3392 3826 4787 2613 05-05-11 1608 4802 3932 4477 2705 05-06-11 1576 3933 3909 4979 2685 05-07-11 95 229 255 496 201 05-08-11 2 0 1 27 0 05-09-11 1438 3785 3589 4174 2215 05-10-11 1342 4043 4009 4665 3033
下面说下如何获取DataFrame里的值:
1.获取某一列: 直接 ['key']
print(ridership_df['R003']) # 结果: 05-01-11 0 05-02-11 1478 05-03-11 1613 05-04-11 1560 05-05-11 1608 05-06-11 1576 05-07-11 95 05-08-11 2 05-09-11 1438 05-10-11 1342 Name: R003, dtype: int64
2.获取某一行: .loc['key']
print(ridership_df.loc['05-01-11']) # 或者 print(ridership_df.iloc[0]) # 结果: R003 0 R004 0 R005 2 R006 5 R007 0 Name: 05-01-11, dtype: int64
3.获取某一行某一列的某个值:
print(ridership_df.loc['05-05-11','R003']) # 或者 print(ridership_df.iloc[4,0]) # 结果: 1608
4.获取原始的numpy二维数组:
print(ridership_df.values) # 结果: [[ 0 0 2 5 0] [1478 3877 3674 2328 2539] [1613 4088 3991 6461 2691] [1560 3392 3826 4787 2613] [1608 4802 3932 4477 2705] [1576 3933 3909 4979 2685] [ 95 229 255 496 201] [ 2 0 1 27 0] [1438 3785 3589 4174 2215] [1342 4043 4009 4665 3033]]
*注意在这过程中,数据格式如果不一致,会发生转换.
一个综合栗子:
从 ridership_df 找出第一天里客流量最多的车站,然后返回这个车站的日平均客流,以及返回所有车站的平均日客流,作为对比:
def mean_riders_for_max_station(ridership): max_index = ridership.iloc[0].argmax() mean_for_max = ridership[max_index].mean() overall_mean = ridership.values.mean() return (overall_mean, mean_for_max) print mean_riders_for_max_station(ridership_df) # 结果: (2342.6, 3239.9)