Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Pandas perform row-wise min() and max() functions?

In my DataFrame I wish to clip the value of a particular column between 0 and 100. For instance, given the following:

  a  b
0 10 90
1 20 150
2 30 -30

I want to get:

  a  b   c
0 10 90  90
1 20 150 100
2 30 -30 0

I know that in Pandas certain arithmetic operations work across columns. For instance, I could double every number in column b like so:

>>>df["c"] = df["b"] * 2
>>>df
  a  b   c
0 10 90  180
1 20 150 300
2 30 -30 -60

However this doesn't work for built-in functions like min and max:

>>>df["c"] = min(100, max(0, df["b"]))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Is there some way to accomplish what I want efficiently?

like image 319
stevendesu Avatar asked Aug 30 '17 17:08

stevendesu


People also ask

How do you get max and min in pandas?

Pandas DataFrame min() Method The min() method returns a Series with the minimum value of each column. By specifying the column axis ( axis='columns' ), the max() method searches column-wise and returns the minimum value for each row.

Does pandas have a row limit?

The short answer is yes, there is a size limit for pandas DataFrames, but it's so large you will likely never have to worry about it. The long answer is the size limit for pandas DataFrames is 100 gigabytes (GB) of memory instead of a set number of cells.

How do I print Max rows in pandas?

Method 2: Using set_option() A function set_option() is provided by pandas to display all rows of the data frame. display. max_rows represents the maximum number of rows that pandas will display while displaying a data frame. The default value of max_rows is 10.

What function in the pandas library can display the maximum rows or columns in a table?

display. max_rows and display. max_columns sets the maximum number of rows and columns displayed when a frame is pretty-printed.


1 Answers

You can use the Pandas min function across an axis. Then combine it with min/max

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.min.html

For example

df.max(axis=1)

But it looks like you want to clip the values instead of min/max.

like image 70
Dat Chu Avatar answered Sep 17 '22 20:09

Dat Chu