import pandas as pd
 
 获取列 首先在pandas中我们想要获取一列,很简单,df[‘A’] 获取行 有loc和iloc的方法 loc:works on labels in the index.(索引+列名) iloc:works on the positions in the index (so it only takes integers).(行号 从0开始)
1 生成DataFrame
 
df = pd.DataFrame(np.arange(0,60,2).reshape(10,3),columns=list(abc))
# np.arange(0,60,2) 表示以2为步长从0走到60 按行来!
df
  
 
  
  
   a b c
  
 
  
  
  
   0 0 2 4
  
 
  
   1 6 8 10
  
 
  
   2 12 14 16
  
 
  
   3 18 20 22
  
 
  
   4 24 26 28
  
 
  
   5 30 32 34
  
 
  
   6 36 38 40
  
 
  
   7 42 44 46
  
 
  
   8 48 50 52
  
 
  
   9 54 56 58
  
 
  
 
2 取第a列
 
2.1 方法1
 
df.loc[:, a] # 取第a列
 
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64
 
2.2 方法2
 
df[a]
 
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64
 
2.3 方法3
 
df.iloc[:, 0]
 
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64
 
3 取倒数第一行的值
 
3.1 法1
 
df.iloc[-1] # 取倒数第一行的值
 
a    54
b    56
c    58
Name: 9, dtype: int64
 
df.iloc[2]
 
a    12
b    14
c    16
Name: 2, dtype: int64
 
df.iloc[-1,:] # 也可以直接用-1即可
 
a    54
b    56
c    58
Name: 9, dtype: int64
 
3.2 方法2
 
df.loc[df.index.max()]
 
a    54
b    56
c    58
Name: 9, dtype: int64
 
df.loc[df.index.max(), :]
 
a    54
b    56
c    58
Name: 9, dtype: int64
 
4 取第1行到第3行
 
df.iloc[1:4]
  
 
  
  
   a b c
  
 
  
  
  
   1 6 8 10
  
 
  
   2 12 14 16
  
 
  
   3 18 20 22
  
 
  
 
5 取第2行第3列的值
 
5.1 方法1
 
df.loc[1, c]
 
10
 
5.2 方法2
 
df.iloc[1, 2]
 
10
 
6 总结
 
 无论是iloc还是loc 均采用[]而不是括号 如果只是取行 建议用iloc 因为比较简单 如果列和行同时取 建议采用loc 因为可以直接定义到标签