pandas-DataFrame布尔索引

介绍

通过布尔值索引,可以实现类似 获取age大于20的记录 的功能

类比:相当于 SQL 中的条件查询

单个值

获取age大于20的记录

print(df[df['Age']>20])

结果如下:

解释
print(df['Age']>20)

返回结果如下:

0       True
1       True
2       True
3       True
4       True
.....
886     True
887    False
888    False
889     True
890     True

第一列是行标签,第二列是布尔值,大于20的显示True,否则显示False,所有行的记录

多个值

逻辑与

逻辑与 符号 &

逻辑或

逻辑或 符号 |

获取age大于70的女性记录

print(df[ (df['Sex']=='female') & (df['Age']>60)])

注意: 条件要用小括号 () 括起来

获取age小于1或者age大于75的记录

print(df[ (df['Age']<1) | (df['Age']>75)])

注意: 条件要用小括号 () 括起来

获取名字长度大于30且年龄大于60的记录

print(df[ (df['Name'].str.len()>30) & (df['Age']>60)])

pandas字符串方法参见链接:
http://www.malaoshi.top/show_1EF3AoIyJM8U.html

获取某行列交集是null的记录

data_frame[data_frame['x'].isnull()]

获取x列中是空值的行

参数
  • column:列标签名
例子
user[user['user_reg_tm'].isnull()]

结果如下:

       user_id  age  sex  user_lv_cd user_reg_tm
34072   234073  NaN  NaN           1         NaN
38905   238906  NaN  NaN           1         NaN
67704   267705  NaN  NaN           1         NaN

user_reg_tm列中是NaN的记录