如何從數(shù)據(jù)框中檢索出自己要的數(shù)據(jù):
data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions',
'Lions', 'Lions'],
'wins': [11, 8, 10, 15, 11, 6, 10, 4],
'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
football = pd.DataFrame(data)
print football['year']
print ''
print football.year # shorthand for football['year']
print ''
print football[['year', 'wins', 'losses']]
這里我們用兩種方式檢索了‘year’這列的數(shù)據(jù)棚壁,也可同時(shí)列出好幾列的數(shù)據(jù):
看結(jié)果:
0 2010
1 2011
2 2012
3 2011
4 2012
5 2010
6 2011
7 2012
Name: year, dtype: int64
0 2010
1 2011
2 2012
3 2011
4 2012
5 2010
6 2011
7 2012
Name: year, dtype: int64
year wins losses
0 2010 11 5
1 2011 8 8
2 2012 10 6
3 2011 15 1
4 2012 11 5
5 2010 6 10
6 2011 10 6
7 2012 4 12
- 獲取某一行的數(shù)據(jù):
football.iloc[[x]],football.loc[[]x]
#獲取第一行的
football.loc[[0]]
football.iloc[0]
- 獲取一個(gè)區(qū)間的行數(shù):
football[x:y]
比如說第2行到底5行的:
football[2:6]
- 根據(jù)某個(gè)條件查詢:
football[條件]
比如獲取勝利場(chǎng)次大于10場(chǎng)的:
football[football.wins > 10]
獲取‘Pachers’隊(duì)勝利超過10場(chǎng)數(shù)據(jù):
football[(football.wins>10) & (football.team == 'Packers')]
下面來跑下數(shù)據(jù)驗(yàn)證上面的方法:
import pandas as pd
data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions',
'Lions', 'Lions'],
'wins': [11, 8, 10, 15, 11, 6, 10, 4],
'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
football = pd.DataFrame(data)
print football.iloc[[0]]
print "---------------------"
print football.loc[[0]]
print "----------------------"
print football[3:5]
print "----------------------"
print football[football.wins > 10]
print "----------------------"
print football[(football.wins > 10) & (football.team == "Packers")]
查看下運(yùn)行結(jié)果:
losses team wins year
0 5 Bears 11 2010
--------------------------------------
losses team wins year
0 5 Bears 11 2010
-----------------------------------
losses team wins year
3 1 Packers 15 2011
4 5 Packers 11 2012
-------------------------------------
losses team wins year
0 5 Bears 11 2010
3 1 Packers 15 2011
4 5 Packers 11 2012
-------------------------------------
losses team wins year
3 1 Packers 15 2011
4 5 Packers 11 2012
Perfect