. 取行的同时,也取列。一个原则是行偷懒的方式和列偷懒的方式都不能用了。必须用.loc或.iloc。
第一种情况是列索引用数字表示, df.iloc[行索引表达,列索引表达],规则跟上面行索引一模一样。
testdf3.iloc[[1,3],[0]] # dataframe
testdf3.iloc[[1,3],0] # series
testdf3.iloc[[1,3],1:3] # dataframe
testdf3.iloc[[1,3],[1,3]]
第二种情况是列索引直接引列名(行索引不存在这个问题,因为pandas没有所谓’行名’),就要用df.loc[行索引,列名索引。
testdf3.loc[1,[“A”,“D”]] # series 对应上述1.1
testdf3.loc[[1],[“A”,“D”]] # df 对应上述1.1
testdf3.loc[[1,3],“A”:“D”] # df 对应上述1.2
testdf3.loc[[1,3],[“A”,“D”]] # df 对应上述1.3
编辑于 2018-11-08
几乎所有的切片操作都可以归结为一种方式
df.loc/iloc[[ A ],[ B ]],
A为列表时指不连续切片,中间有冒号时为连续切片,B同理
1.2 第二种情况是取连续的某几行。用df.iloc[行号:行号],也可以偷懒用df[行号:行号]。得到的都是df.
testdf3[2:3] # data frame
testdf3.iloc[2:3] # data frame
1.3 第三种情况是不连续的多行,则是df.iloc[[行号,行