Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace negative values in single DataFrame column

Tags:

python

pandas

If I have the following DataFrame:

>>> df_1 = pd.DataFrame({'A':[-1, 2,  3],
                         'B':[4, -5,  6],
                         'C':[7,  8, -9]}, 
                          index=pd.to_datetime(['2017-01-01 00:01:00', '2017-01-01 00:02:00', '2017-01-02 00:01:00']))

>>> df_1
                      A   B   C
2017-01-01 00:01:00  -1   4   7
2017-01-01 00:02:00   2  -5   8
2017-01-02 00:01:00   3   6  -9

How would I replace all of the negative values in a specific column with something else? For example, if I want to replace all of the negative values in the 'B' column but none of the others with, say 0, the following would be my result.

>>> df_2
                      A   B   C
2017-01-01 00:01:00  -1   4   7
2017-01-01 00:02:00   2   0   8
2017-01-02 00:01:00   3   6  -9
like image 620
mitchute Avatar asked Apr 05 '18 20:04

mitchute


People also ask

How do I change the value of a column in a Dataframe?

Use the replace() Method to Modify Values. Another way to replace column values in Pandas DataFrame is the Series.replace() method. Series.replace() Syntax. Replace one single value; df[column_name].replace([old_value], new_value) Replace multiple values with the same value; df[column_name].replace([old_value1, old_value2, old_value3], new_value)

How to replace values in pandas Dataframe?

Depending on your needs, you may use either of the following methods to replace values in Pandas DataFrame: (1) Replace a single value with a new value for an individual DataFrame column: (2) Replace multiple values with a new value for an individual DataFrame column:

How to replace the negative numbers by zero in pandas?

In this article, Let’s discuss how to replace the negative numbers by zero in Pandas . 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.

How to replace values in a data frame in R?

Replacing values in a data frame is a very handy option available in R for data analysis. Using replace () in R, you can switch NA, 0, and negative values with appropriate to clear up large datasets for analysis. Congratulations, you learned to replace the values in R. Keep going!


1 Answers

I think you can using mask

df_1.B=df_1.B.mask(df_1.B.lt(0),0)
df_1
Out[1437]: 
                     A  B  C
2017-01-01 00:01:00 -1  4  7
2017-01-01 00:02:00  2  0  8
2017-01-02 00:01:00  3  6 -9

If we combine with fillna ()Assuming different columns should fill will different value)

df_1.mask(df_1.lt(0)).fillna({'A':9999,'B':0,'C':-9999})
Out[1440]: 
                          A    B       C
2017-01-01 00:01:00  9999.0  4.0     7.0
2017-01-01 00:02:00     2.0  0.0     8.0
2017-01-02 00:01:00     3.0  6.0 -9999.0
like image 165
BENY Avatar answered Sep 30 '22 20:09

BENY