AUK1939
AUK1939

Reputation: 659

Strange behaviour when adding columns

I'm using Python 2.7.8 |Anaconda 2.1.0. I'm wondering why the strange behavior below occurs

I create a pandas dataframe with two columns, then add a third column by summing the first two columns

x = pd.DataFrame(np.random.randn(5, 2), columns = ['a', 'b'])
x['c'] = x[['a', 'b']].sum(axis = 1) #or x['c'] = x['a'] + x['b'] 
Out[7]: 
          a         b         c
0 -1.644246  0.851602 -0.792644
1 -0.129092  0.237140  0.108049
2  0.623160  0.105494  0.728654
3  0.737803 -1.612189 -0.874386
4  0.340671 -0.113334  0.227337

All good so far. Now I want to set the values of column c to zero if they are negative

x[x['c']<0] = 0
Out[9]: 
          a         b         c
0  0.000000  0.000000  0.000000
1 -0.129092  0.237140  0.108049
2  0.623160  0.105494  0.728654
3  0.000000  0.000000  0.000000
4  0.340671 -0.113334  0.227337

This gives the desired result in column 'c', but for some reason columns 'a' and 'b' have been modified - i don't want this to happen. I was wondering why this is happening and how I can fix this behavior?

Upvotes: 0

Views: 45

Answers (2)

Kathirmani Sukumar
Kathirmani Sukumar

Reputation: 10970

Because you are setting to zero for all the columns. You should set it only for column c

x['c'][x['c']<0] = 0

Upvotes: 1

joris
joris

Reputation: 139172

You have to specify you only want the 'c' column:

x.loc[x['c']<0, 'c'] = 0

When you just index with a boolean array/series, this will select full rows, as you can see in this example:

In [46]: x['c']<0
Out[46]:
0     True
1    False
2    False
3     True
4    False
Name: c, dtype: bool

In [47]: x[x['c']<0]
Out[47]:
          a         b         c
0 -0.444493 -0.592318 -1.036811
3 -1.363727 -1.572558 -2.936285

Upvotes: 2

Related Questions