选择pandas DataFrame的行,其中列不是空列表 [英] Selecting rows of pandas DataFrame where column is not empty list

查看:190
本文介绍了选择pandas DataFrame的行,其中列不是空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas DataFrame,其中一列包含列表,并希望选择列表不为空的行.

I have a pandas DataFrame where one column contains lists and would like to select the rows where the lists are not empty.

示例数据:

df = pd.DataFrame({'letter': ["a", "b", "c", "d", "e"], 
               'my_list':[[0,1,2],[1,2],[],[],[0,1]]})

df
    letter   my_list
0   a   [0, 1, 2]
1   b   [1, 2]
2   c   []
3   d   []
4   e   [0, 1]

我想要的东西:

df
    letter  my_list
0   a   [0, 1, 2]
1   b   [1, 2]
4   e   [0, 1]

我正在尝试:

df[df.my_list.map(lambda x: if len(x) !=0)]

...,它返回无效的语法错误.有什么建议吗?

... which returns an invalid syntax error. Any suggestions?

推荐答案

在布尔上下文中,空列表的值为False

Empty lists evaluate to False in a boolean context

df[df.my_list.astype(bool)]

  letter    my_list
0      a  [0, 1, 2]
1      b     [1, 2]
4      e     [0, 1]

这篇关于选择pandas DataFrame的行,其中列不是空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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