Python: Pandas filter string data based on its string length

后端 未结 6 1221
眼角桃花
眼角桃花 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:15

    import pandas as pd
    
    df = pd.read_csv('filex.csv')
    df['A'] = df['A'].astype('str')
    df['B'] = df['B'].astype('str')
    mask = (df['A'].str.len() == 10) & (df['B'].str.len() == 10)
    df = df.loc[mask]
    print(df)
    

    Applied to filex.csv:

    A,B
    123,abc
    1234,abcd
    1234567890,abcdefghij
    

    the code above prints

                A           B
    2  1234567890  abcdefghij
    

提交回复
热议问题