DataFrame 的访问:[]选择列,[[]]选择多列,loc[]选择行,loc[[]]选择多行,iloc[],at[],iat[],ix[],loc[]行列切片,布尔选择

http://liao.cpython.org/pandas10/
http://liao.cpython.org/pandas11/

[]选择列:DataFrame使用了[ ]则是选择了一个字段所有数据即一列,而Series则是会得到某行的数据。

val = np.arange(10,40).reshape(10,3)
idx = 'ax bx cx'.split()
df1 = pd.DataFrame(val,columns = idx)

df1['ax']
Out[214]: 
0    10
1    13
2    16
3    19
4    22
5    25
6    28
7    31
8    34
9    37
Name: ax, dtype: int32

选择多列 [[ ]]

df1[['ax','bx']]
Out[216]: 
   ax  bx
0  10  11
1  13  14
2  16  17
3  19  20
4  22  23
5  25  26
6  28  29
7  31  32
8  34  35
9  37  38

loc[] 选择行

df1.loc[1]
Out[224]: 
ax    13
bx    14
cx    15
Name: 1, dtype: int32

loc[[ ]]选择多行

df1.loc[[0,1]]
Out[223]: 
   ax  bx  cx
0  10  11  12
1  13  14  15
type(df1.loc[0])
Out[225]: pandas.core.series.Series

type(df1.loc[[0,1]])
Out[226]: pandas.core.frame.DataFrame

iloc[]选择行:与loc[]不同之处,iloc[]里是位置信息,而loc[]里是标签信息。

省略

at[] 选择标签指定某值,尽量还是用label的形式

val = np.arange(10,40).reshape(10,3)
idx = 'ax bx cx'.split()
label = 'a b c d e f g h i j'.split()
df1 = pd.DataFrame(val,columns = idx,index = label)

df1.at['e','cx']
Out[230]: 24

iat[ ] 选择位置上的值

ix[]混合选择:ix[]的[]里可以是label数据和位置数据的混合使用。

**小结:在at、iat、ix等先给出的是行信息,后边是列信息。

在pandas里DataFrame[label]或者DataFrame[index]选择的是列。而DataFrame[start:end]则是通过切片选择的是行。

val = np.arange(10,40).reshape(10,3)
idx = 'ax bx cx'.split()
label = 'a b c d e f g h i j'.split()
df1 = pd.DataFrame(val,columns = idx,index = label)

Out[236]: 
   ax  bx  cx
a  10  11  12
b  13  14  15
c  16  17  18
d  19  20  21
e  22  23  24
f  25  26  27
g  28  29  30
h  31  32  33
i  34  35  36
j  37  38  39

df1['ax']
Out[237]: 
a    10
b    13
c    16
d    19
e    22
f    25
g    28
h    31
i    34
j    37
Name: ax, dtype: int32

df1['a':'c']
Out[238]: 
   ax  bx  cx
a  10  11  12
b  13  14  15
c  16  17  18

在DataFrame的[]里用切片很难选择多行多列数据,但DataFrame的loc、iloc等可以通过切片选择多行多列数据。

df1.loc['a']  #这里选择出来的是行
Out[239]: 
ax    10
bx    11
cx    12
Name: a, dtype: int32

df1.loc['a':'c','ax':'cx'] #同样的loc, 切出来是行+列的切片
Out[240]: 
   ax  bx  cx
a  10  11  12
b  13  14  15
c  16  17  18

iloc[]行列切片:在iloc里给出位置信息的行、列切片也可以实现块选择,尽量还是用loc[]位置切片!!

布尔选择

  • 7
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值