Selecting rows of pandas DataFrame where column is not empty list

感情迁移 提交于 2019-12-19 19:14:02

问题


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

Example data:

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]

What I'd like:

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

What I'm trying:

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

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


回答1:


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]



回答2:


Or you can follow your own logic using length of the list to determine keep or not .

df[df.my_list.str.len().gt(0)]
Out[1707]: 
  letter    my_list
0      a  [0, 1, 2]
1      b     [1, 2]
4      e     [0, 1]


来源:https://stackoverflow.com/questions/49700794/selecting-rows-of-pandas-dataframe-where-column-is-not-empty-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!