PANDAS第二次打卡

2021-10-05 09:43:21 字數 2167 閱讀 4663

第2章 索引

import numpy as np

import pandas as pd

df = pd.read_csv(『data/table.csv』,index_col=『id』)

df.head()

school class gender address height weight math physics

id 1101 s_1 c_1 m street_1 173 63 34.0 a+

1102 s_1 c_1 f street_2 192 73 32.5 b+

1103 s_1 c_1 m street_2 186 82 87.2 b+

1104 s_1 c_1 f street_2 167 81 80.4 b-

1105 s_1 c_1 f street_4 159 64 84.8 b+

一、單級索引

loc方法、iloc方法、操作符

最常用的索引方法可能就是這三類,其中iloc表示位置索引,loc表示標籤索引,也具有很大的便利性,各有特點

(a)loc方法(注意:所有在loc中使用的切片全部包含右端點!)

① 單行索引:

df.loc[1103]

school s_1

class c_1

gender m

address street_2

height 186

weight 82

math 87.2

physics b+

name: 1103, dtype: object

② 多行索引:

df.loc[[1102,2304]]

school class gender address height weight math physics

id 1102 s_1 c_1 f street_2 192 73 32.5 b+

2304 s_2 c_3 f street_6 164 81 95.5 a-

df.loc[1304:].head()

school class gender address height weight math physics

id 1304 s_1 c_3 m street_2 195 70 85.2 a

1305 s_1 c_3 f street_5 187 69 61.7 b-

2101 s_2 c_1 m street_7 174 84 83.3 c

2102 s_2 c_1 f street_6 161 61 50.6 b+

2103 s_2 c_1 m street_4 157 61 52.5 b-

df.loc[2402::-1].head()

school class gender address height weight math physics

id 2402 s_2 c_4 m street_7 166 82 48.7 b

2401 s_2 c_4 f street_2 192 62 45.3 a

2305 s_2 c_3 m street_4 187 73 48.9 b

2304 s_2 c_3 f street_6 164 81 95.5 a-

2303 s_2 c_3 f street_7 190 99 65.9 c

③ 單列索引:

df.loc[:,『height』].head()

id1101 173

1102 192

1103 186

1104 167

1105 159

name: height, dtype: int64

④ 多列索引:

df.loc[:,[『height』,『math』]].head()

height math

id 1101 173 34.0

1102 192 32.5

1103 186 87.2

1104 167 80.4

1105 159 84.8

df.loc[:,『height』:『math』].head()

height weight math

id 1101 173 63 34.0

1102 192 73 32.5

1103 186 82 87.2

1104 167 81 80.4

1105 159 64 84.8

第二次打卡

主成分分析法 principal component analysis,pca 就是一種運用線性代數的知識來進行資料降維的方法,它將多個變數轉換為少數幾個不相關的綜合變數來比較全面地反映整個資料集。這是因為資料集中的原始變數之間存在一定的相關關係,可用較少的綜合變數來綜合各原始變數之間的資訊。這些綜...

python第二次打卡

if 語句的 expr true suite 塊只有當條件表示式 expression 結果為真時才執行,否則將繼續執行緊跟在該 塊後面的語句。單個 if 語句中的 expression 條件表示式可以通過布林操作符 and,or和not 實現多重條件判斷。python 提供與 if 搭配使用的 e...

學習筆記第二次打卡

讀入文字 分詞建立字典,將每個詞對映到乙個唯一的索引 index 將文字從詞的序列轉換為索引的序列,方便輸入模型 建立詞典 class vocab object def init self,tokens,min freq 0,use special tokens false counter coun...