pandas数据操作(二)

dataframe中的数据切片/数据选取

  • 根据索引选取数据
#选取'索引'对应的列
df['索引1','索引2','索引3'...]

#选取'索引1'和'索引2'之间的列
df['索引1':'索引2']
  • ix:支持基于混合整数和标签的访问,它支持.loc和iloc的任何输入,还支持浮点标签。
  • iloc:根据位置的整数索引选取数据
#选取第六行数据
df.iloc[5]  #输入行索引

#选取低2,4,6行数据
df.iloc[[1,3,5]]

#选取2-4行数据(不含第四行)
df.iloc[1:3]

#选取第1,3行数据(布尔数组)
df.iloc[[True,Flase,True]]

#选取'索引'列中大于10 的行数据
df.iloc[(df['索引']>10).tolist()]

df.iloc[(df['索引']>10)]
注意:iloc接受有返回值的函数作为参数,但要保证函数返回的是整数/整数list,布尔值/布尔list

#如果直接运行 df.iloc[df[‘one’]>10]
#则会报错 NotImplementedError: iLocation based boolean indexing on an integer type is not available
#因为df['索引'] > 10 返回的是 series类型的数据

#选取第6行,第2列的数据
df.iloc[5,1]

#选取第1,3行,1,2列的数据
df.iloc[[1,3],[1,2]]

#选取第2,3行,2,3列的数据
df.iloc[1:3,1:3]

#选取第1,4行,1,3列的数据
df.iloc[[1,5],[1,4]]
  • loc:从索引中获取具有特定标签的行(或列)
#选取行标签为'行索引'那一行
df.loc['行索引']

#选取行标签为'行索引1','行索引2'的两行
df.loc[['行索引1','行索引2']]

#选取从'行索引1'到'行索引2'的'列索引'
df.loc['行索引1':'行索引2','列索引']

#选取'列索引1'一列大于6的那一行的'列索引2'数据
df.loc[df['列索引1'] > 6, ['列索引2']]

#选取'列索引'列中所有大于10 的行
df.loc[df['列索引']>10]

TAG:none

发表新评论