How can I select Pandas.DataFrame by elements' length

前端 未结 2 1697

How can I select Pandas.DataFrame by elements\' length.

import pandas as pd;
import numpy as np;

df=pd.DataFrame(np.random.randn(4,4).astype(str))

df.apply(lam         


        
2条回答
  •  失恋的感觉
    2021-01-24 17:56

    Here is a simple example to show you what is going on:

    import pandas as pd
    import numpy as np
    
    df=pd.DataFrame(np.random.randn(4,4).astype(str))
    
    lengths = df.apply(lambda x: len(x[0]))
    mask = lengths < 15
    
    print df
    print lengths
    print mask
    print df[mask]
    

    Results in:

                     0                1                 2                 3 
    0   0.315649003654   -1.20005871043  -0.0973557747322  -0.0727740019505 
    1  -0.270800223158   -2.96509489589    0.822922470677     1.56021584947 
    2   -2.36245475786  0.0763821870378      1.0540009757   -0.452842084388 
    3   -1.03486927366  -0.269946751202   0.0611709385483   0.0114964425747 
    
    0    14 
    1    14 
    2    16 
    3    16 
    dtype: int64 
    
    0     True 
    1     True 
    2    False 
    3    False 
    dtype: bool 
    
                     0               1                 2                 3 
    0   0.315649003654  -1.20005871043  -0.0973557747322  -0.0727740019505 
    1  -0.270800223158  -2.96509489589    0.822922470677     1.56021584947 
    

提交回复
热议问题