Pandas:为什么在布尔索引后选择列需要双括号 [英] Pandas: Why are double brackets needed to select column after boolean indexing

查看:957
本文介绍了Pandas:为什么在布尔索引后选择列需要双括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如下所示的df表,

For a df table like below,

   A B C D
0  0 1 1 1
1  2 3 5 7
3  3 1 2 8

为什么需要双括号来选择具体的布尔索引后的列?

why are the double brackets needed for selecting specific columns after boolean indexing?

the [['A','C']] part of

df[df['A'] < 3][['A','C']]


推荐答案

对于pandas对象(Series,DataFrame),索引操作符[]只接受

For pandas objects (Series, DataFrame), the indexing operator [] only accepts


  1. colname 或用于选择列的colnames列表

  2. 切片或布尔数组以选择行,即它仅指数据帧的一个维度。

  1. colname or list of colnames to select column(s)
  2. slicing or Boolean array to select row(s), i.e. it only refers to one dimension of the dataframe.

对于 df [[colname(s)]] ,内部括号用于列表,外部括号是索引操作符,即如果选择两列或更多列,则必须使用双括号。使用一个列名称,一对括号返回一个Series,而双括号返回一个数据帧。

For df[[colname(s)]], the interior brackets are for list, and the outside brackets are indexing operator, i.e. you must use double brackets if you select two or more columns. With one column name, single pair of brackets returns a Series, while double brackets return a dataframe.

此外, df.ix [df [' A']< 3,['A','C']] df.loc [df ['A']< 3,['A','C']] 优于链式选择,以避免返回副本与数据帧的视图。

Also, df.ix[df['A'] < 3,['A','C']] or df.loc[df['A'] < 3,['A','C']] is better than the chained selection for avoiding returning a copy versus a view of the dataframe.

请参阅 pandas文档了解详情

这篇关于Pandas:为什么在布尔索引后选择列需要双括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆