bill
bill

Reputation: 722

how to clip pandas dataframe column-wise?

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)

I got

ValueError: other must be the same shape as self when an ndarray

Is that expected? I was expecting to get something like:

Out[72]:

     0    1    2
0  1.5  2.5  3.5
1  4.0  5.0  6.0

Upvotes: 9

Views: 7977

Answers (2)

user2285236
user2285236

Reputation:

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

Upvotes: 10

su79eu7k
su79eu7k

Reputation: 7316

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

Upvotes: 0

Related Questions