索引
import pandas as pd
ser=pd.Series(range(0,10,2))
print(ser)
0 0
1 2
2 4
3 6
4 8
dtype: int64
通過索引值或索引標簽獲取資料
通過index查看索引值
print(ser.index)
RangeIndex(start=0, stop=5, step=1)
自定義索引值
ser.index=['a','b','c','d','f']
print(ser)
a 0
b 2
c 4
d 6
f 8
dtype: int64
通過索引值和索引標簽獲取資料
print('ser[3]:',ser[3])
print('ser[d]:',ser['d'])
print('ser[[1,2,3]]:',ser[[1,2,3]])
print("ser[['a','b','c']]:",ser[['a','b','c']])
print('ser[3:]:',ser[3:])
ser[3]: 6
ser[d]: 6
ser[[1,2,3]]: b 2
c 4
d 6
dtype: int64
ser[['a','b','c']]: a 0
b 2
c 4
dtype: int64
ser[3:]: d 6
f 8
dtype: int64
自動化對齊
如果對兩個序列進行運算,索引就會將元素對齊進行運算
a=pd.Series([1,2,3,4,5,6],index=['a','b','c','d','f','g'])
print(a)
b=pd.Series([4,5,6,7,8,9],index=['g','f','d','c','b','a'])
print(b)
print(a+b)
a 1
b 2
c 3
d 4
f 5
g 6
dtype: int64
g 4
f 5
d 6
c 7
b 8
a 9
dtype: int64
a 10
b 10
c 10
d 10
f 10
g 10
dtype: int64
利用pandas查詢資料
import pandas as pd
stu_dic={
'name':['a','b','c','d','e','f','g','h'],
'age':[18,15,45,56,89,78,45,12],
'sex':['f','m','m','f','f','f','m','m']
}
student=pd.DataFrame(stu_dic)
print(student)
name age sex
0 a 18 f
1 b 15 m
2 c 45 m
3 d 56 f
4 e 89 f
5 f 78 f
6 g 45 m
7 h 12 m
查詢資料前5行或后5行
# 查詢前5行
student.head()
# 查詢后5行
student.tail()
# 查詢前5行
print(student.head())
print('* '*10)
#查詢后5行
print(student.tail())
name age sex
0 a 18 f
1 b 15 m
2 c 45 m
3 d 56 f
4 e 89 f
* * * * * * * * * *
name age sex
3 d 56 f
4 e 89 f
5 f 78 f
6 g 45 m
7 h 12 m
查詢指定的行
student.loc[[1,2,3]]
loc標簽索引函式必須是中括號
# 查詢第1,2,3行
print(student.loc[[1,2,3]])
name age sex
1 b 15 m
2 c 45 m
3 d 56 f
查詢指定的列
student[['name','age']]
如果查詢多個列,必須使用雙重中括號
# 查詢name,age列
print(student[['name','age']])
name age
0 a 18
1 b 15
2 c 45
3 d 56
4 e 89
5 f 78
6 g 45
7 h 12
查詢18歲以上女生資訊
student[(student['sex']=='f')&(student['age']>=18)]
print(student[(student['sex']=='f')&(student['age']>=18)])
name age sex
0 a 18 f
3 d 56 f
4 e 89 f
5 f 78 f
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/98271.html
標籤:Python
