pandas的索引操作可以快速的完成多種功能。
import pandas as pd import numpy as np
1. 首先pandas創建DataFrame,創建DataFrame格式數據有多種方式,可以使用數組、列表、字典等;
df_1 = pd.DataFrame([['Jack','M',40],['Tony','M',20],['Mary','F',30],['Bob','M',25]], columns=['name','gender','age']) #列表創建DataFrame print('------ df_1是: ------') print(df_1)
2. 直接列名檢索
# 列名索引 a = df_1['name'] print(a)
3. 同時取多列數據
# 同時取多列 b = df_1[['name','age']] print(b)
4. 切片索引
# 切片索引,按行索引 bb = df_1[1:3] print(bb)
5. 條件索引
aa = df_1[df_1.age>25] print(aa)
6. isin判斷
# isin 索引 cc = df_1[df_1.name.isin(['Jack','Bob'])] print(cc)
7. loc取行數據
# loc取行 dd = df_1.loc[df_1.name.isin(['Jack','Bob'])] #去滿足條件的所有行 print(dd)
8. loc標簽
# loc取行 ee = df_1.loc[1:3] #直接按照標簽取,不是屬於切片,所以會1-3行全部取出來 print(ee)
9. 多個條件,'|' 條件取行('或'條件),邏輯條件
ff = df_1.loc[df_1.name.isin(['Jack','Bob']) | (df_1.age>25)] #多個條件,'|'條件取行 print('the value of ff is: ') print(ff) print(df_1.name.isin(['Jack','Bob']) | (df_1.age>25))
10. 多個條件取行,'&' 條件取行,('與' 條件),邏輯條件
gg = df_1.loc[df_1.name.isin(['Jack','Bob']) & (df_1.age>25)] #多個條件取行,'&'條件取行 print('the value of gg is: ') print(gg) print(df_1.name.isin(['Jack','Bob']) & (df_1.age>25))
11. loc 按行、列條件取值,取其中某列,可用來取某一行某一列的值(也就是某個位置的值)
hh = df_1.loc[df_1.name.isin(['Jack','Bob']) | (df_1.age>25), 'age'] print(hh)
12. loc多行、列取值,取多行多列
ii = df_1.loc[1:3, 'name':'gender'] # 'name':'gender'順序有前后 print('the value of ii is: ') print(ii)
13. iloc:切片
jj = df_1.iloc[1:3] #此時按照切片規則取行 print('the value of jj is: ') print(jj)
14. ix:之前的方法,現在可以用loc和iloc來實現,執行的時候會出現:DeprecationWarning: .ix is deprecated. Please use .loc for label based indexing or .iloc for positional indexing。
mm = df_1.ix[1:3] #此時按照標簽規則取行,而不是切片規則 print('the value of mm is: ') print(mm)
nn = df_1.ix[1:3, 'name':'gender'] #此時按照標簽規則取行,而不是切片規則 print('the value of nn is: ') print(nn)
15. 如果其中的值都是數字,可以對整體進行限定,例如:
array_test = np.array([[1,2,3,4],[2,3,4,5],[3,4,5,6]]) df_3 = pd.DataFrame(array_test, index = ['aa', 'bb', 'ff'], columns = ['c1', 'c2', 'c3', 'c4']) #數組創建DataFrame print('------ df_3是: ------') print(df_3)
# 取滿足條件的值:
df_4 = df_3[df_3>3] #取滿足條件的值 print('the value of df_4 is :') print(df_4)
# 將滿足條件的值重新賦值:
df_3[df_3>3]=0 #將滿足條件的值重新賦值 print('the value of df_3 is :') print(df_3)
##