Is there any way to replace all DataFrame negative numbers by zeros?
Jul 8, 2019 in Python 44,060 views

## 3 answers to this question.

If all your columns are numeric, you can use boolean indexing:

```In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})

In [3]: df
Out[3]:
a  b
0  0 -3
1 -1  2
2  2  1

In [4]: df[df < 0] = 0

In [5]: df
Out[5]:
a  b
0  0  0
1  0  2
2  2  1```

For the more general case, this shows the private method _get_numeric_data:

```In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1],
'c': ['foo', 'goo', 'bar']})

In [3]: df
Out[3]:
a  b    c
0  0 -3  foo
1 -1  2  goo
2  2  1  bar

In [4]: num = df._get_numeric_data()

In [5]: num[num < 0] = 0

In [6]: df
Out[6]:
a  b    c
0  0  0  foo
1  0  2  goo
2  2  1  bar```
• 13,300 points

Approach:

• Import pandas module.
• Create a Dataframe.
• Check the DataFrame element is less than zero, if yes then assign zero in this element.
• Display the final DataFrame

First, let’s create the dataframe.

• Python3
 ```# importing pandas module import pandas as pd # Creating pandas DataFrame df = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6], "B": [3, -5, -6, 7, 3, -2], "C": [-4, 5, 6, -7, 5, 4], "D": [34, 5, 32, -3, -56, -54]}) # Displaying the original DataFrame print("Original Array : ") df```

Output :

• 65,890 points

If all your columns are numeric, you can use boolean indexing: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1]})  For the more general case, this shows the private method _get_numeric_data: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'a': [0, -1, 2], 'b': [-3, 2, 1], 'c': ['foo', 'goo', 'bar']}) In [3]: df Out[3]: a b c 0 0 -3 foo 1 -1 2 goo 2 2 1 bar In [4]: num = df._get_numeric_data() In [5]: num[num < 0] = 0 In [6]: df Out[6]: a b c 0 0 0 foo 1 0 2 goo 2 2 1 bar

• 8,910 points

## How to replace entire column in pandas dataframe?

Use the dataframe with respective column names ...READ MORE

## How to convert each list item into string in a column of data frame. ?

Hey, To split a string you can use ...READ MORE

## How to append new data in pandas DataFrame?

Hi@MD, You can use the append function to ...READ MORE

## How to replace values with None in Pandas data frame in Python?

Actually in later versions of pandas this ...READ MORE

## how do i change string to a list?

suppose you have a string with a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE