Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clip pandas dataframe column-wise?

Tags:

python

pandas

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
like image 811
bill Avatar asked Feb 14 '17 04:02

bill


People also ask

How do you slice a DataFrame for specific columns?

To slice the columns, the syntax is df. loc[:,start:stop:step] ; where start is the name of the first column to take, stop is the name of the last column to take, and step as the number of indices to advance after each extraction; for example, you can select alternate columns.

How do you clip values in Pandas?

clip() is used to trim values at specified input threshold. We can use this function to put a lower limit and upper limit on the values that any cell can have in the dataframe.

Can you slice a DataFrame?

Slicing a DataFrame in Pandas includes the following steps:Ensure Python is installed (or install ActivePython) Import a dataset. Create a DataFrame. Slice the DataFrame.


1 Answers

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
like image 133
ayhan Avatar answered Sep 20 '22 18:09

ayhan