Python: Pandas Dataframe how to multiply entire co

2020-02-07 17:46发布

How do I multiply each element of a given column of my dataframe with a scalar? (I have tried looking on SO, but cannot seem to find the right solution)

Doing something like:

df['quantity'] *= -1 # trying to multiply each row's quantity column with -1

gives me a warning:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Note: If possible, I do not want to be iterating over the dataframe and do something like this...as I think any standard math operation on an entire column should be possible w/o having to write a loop:

for idx, row in df.iterrows():
    df.loc[idx, 'quantity'] *= -1

EDIT:

I am running 0.16.2 of Pandas

full trace:

 SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s

10条回答
疯言疯语
2楼-- · 2020-02-07 18:09

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

查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-07 18:10

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.

查看更多
一纸荒年 Trace。
4楼-- · 2020-02-07 18:12

try using apply function.

df['quantity'] = df['quantity'].apply(lambda x: x*-1)
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-07 18:12

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

df.loc[:, 'quantity'] = df['quantity'] * -1
查看更多
登录 后发表回答