How to remove a row from pandas dataframe based on the length of the column values?

后端 未结 5 1941
失恋的感觉
失恋的感觉 2021-01-17 10:16

In the following pandas.DataFframe:

df = 
    alfa    beta   ceta
    a,b,c   c,d,e  g,e,h
    a,b     d,e,f  g,h,k
    j,k     c,k,l  f,k,n
         


        
5条回答
  •  天涯浪人
    2021-01-17 10:54

    How's this?

    df = df[df['alpha'].str.split(',', expand=True)[2].isnull()]
    

    Using expand=True creates a new dataframe with one column for each item in the list. If the list has three or more items, then the third column will have a non-null value.

    One problem with this approach is that if none of the lists have three or more items, selecting column [2] will cause a KeyError. Based on this, it's safer to use the solution posted by @Stephen Rauch.

提交回复
热议问题