Reputation: 1577
How do I multiply only specific columns of a dataframe by a constant value?
df0 = pd.DataFrame({'A' : 1.,
'B' : 1,
'C' : 1,
'D' : np.array([1] * 4,dtype='int32')})
mult_by_two = df0.iloc[:,2:].mul(2)
print mult_by_two
I get this:
C D
0 2 2
1 2 2
2 2 2
3 2 2
but what I want is this:
A B C D
0 1 1 2 2
1 1 1 2 2
2 1 1 2 2
3 1 1 2 2
Upvotes: 2
Views: 14122
Reputation: 31672
If you need to multiply on scalar you don't need to call mul
method you could use usual *
operator:
In [24]: df0.iloc[:,2:] * 2
Out[24]:
C D
0 2 2
1 2 2
2 2 2
3 2 2
For your question you could use pd.concat
with your first columns and columns you are multiplying:
In [25]: pd.concat([df0.iloc[:,:2], df0.iloc[:,2:] * 2], axis=1)
Out[25]:
A B C D
0 1 1 2 2
1 1 1 2 2
2 1 1 2 2
3 1 1 2 2
Upvotes: 2
Reputation: 85482
You can assign the result to df0
:
>>> df0.iloc[:,2:] = df0.iloc[:,2:].mul(2)
>>> df0
A B C D
0 1 1 2 2
1 1 1 2 2
2 1 1 2 2
3 1 1 2 2
If you want a copy, make before the assigment:
df1 = df0.copy()
df1.iloc[:,2:] = df1.iloc[:,2:].mul(2)
Upvotes: 6