how to clip pandas dataframe column-wise?

后端 未结 2 1255
一个人的身影
一个人的身影 2021-01-05 03:38

I have

In [67]: a
Out[67]:

   0  1  2
0  1  2  3
1  4  5  6

when I run

In [69]: a.clip(lower=[1.5,2.5,3.5],axis=1)
         


        
相关标签:
2条回答
  • 2021-01-05 04:14

    lower : float or array_like, default None

    According to API reference, you're supposed to use same shaped array.

    import numpy as np
    import pandas as pd
    
    ...
    
    print df.shape
    
    (2, 3)
    
    print df.clip(lower=(df.clip(lower=(np.array([[n+1.5 for n in range(df.shape[1])] for _ in range(df.shape[0])])), axis=1))
    
         0    1    2
    0  1.5  2.5  3.5
    1  4.0  5.0  6.0
    
    0 讨论(0)
  • 2021-01-05 04:31

    Instead of a numpy array, you can use a Series so the labels are aligned:

    df
    Out: 
       A  B
    0  1  4
    1  2  5
    2  3  6
    
    df.clip(lower=pd.Series({'A': 2.5, 'B': 4.5}), axis=1)
    Out: 
         A    B
    0  2.5  4.5
    1  2.5  5.0
    2  3.0  6.0
    
    0 讨论(0)
提交回复
热议问题