Python: Pandas filter string data based on its string length

后端 未结 6 1220
眼角桃花
眼角桃花 2020-12-01 08:35

I like to filter out data whose string length is not equal to 10.

If I try to filter out any row whose column A\'s or B\'s string length is not equal to 10, I tried

6条回答
  •  不思量自难忘°
    2020-12-01 09:23

    A more Pythonic way of filtering out rows based on given conditions of other columns and their values:

    Assuming a df of:

    data={"names":["Alice","Zac","Anna","O"],"cars":["Civic","BMW","Mitsubishi","Benz"],
         "age":["1","4","2","0"]}
    
    df=pd.DataFrame(data)
    df:
      age        cars  names
    0   1       Civic  Alice
    1   4         BMW    Zac
    2   2  Mitsubishi   Anna
    3   0        Benz      O
    

    Then:

    df[
    df['names'].apply(lambda x: len(x)>1) &
    df['cars'].apply(lambda x: "i" in x) &
    df['age'].apply(lambda x: int(x)<2)
      ]
    

    We will have :

      age   cars  names
    0   1  Civic  Alice
    

    In the conditions above we are looking first at the length of strings, then we check whether a letter ("i") exists in the strings or not, finally, we check for the value of integers in the first column.

提交回复
热议问题