Python: Pandas Dataframe how to multiply entire column with a scalar

♀尐吖头ヾ 提交于 2019-11-28 17:46:00

try using apply function.

df['quantity'] = df['quantity'].apply(lambda x: x*-1)

Here's the answer after a bit of research:

df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning 
DJK

Note: for those using pandas 0.20.3 and above, and are looking for an answer, all these options will work:

df = pd.DataFrame(np.ones((5,6)),columns=['one','two','three',
                                       'four','five','six'])
df.one *=5
df.two = df.two*5
df.three = df.three.multiply(5)
df['four'] = df['four']*5
df.loc[:, 'five'] *=5
df.iloc[:, 5] = df.iloc[:, 5]*5

which results in

   one  two  three  four  five  six
0  5.0  5.0    5.0   5.0   5.0  5.0
1  5.0  5.0    5.0   5.0   5.0  5.0
2  5.0  5.0    5.0   5.0   5.0  5.0
3  5.0  5.0    5.0   5.0   5.0  5.0
4  5.0  5.0    5.0   5.0   5.0  5.0

More recent pandas versions have the pd.DataFrame.multiply function.

df['quantity'] = df['quantity'].multiply(-1)

A bit old, but I was still getting the same SettingWithCopyWarning. Here was my solution:

df.loc[:, 'quantity'] = df['quantity'] * -1

Try df['quantity'] = df['quantity'] * -1.

I got this warning using Pandas 0.22. You can avoid this by being very explicit using the assign method:

df = df.assign(quantity = df.quantity.mul(-1))

A little late to the game, but for future searchers, this also should work:

df.quantity = df.quantity  * -1

You can use the index of the column you want to apply the multiplication for

df.loc[:,6] *= -1

This will multiply the column with index 6 with -1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!