Python:Pandas Dataframe如何将整个列与标量相乘 [英] Python: Pandas Dataframe how to multiply entire column with a scalar
本文介绍了Python:Pandas Dataframe如何将整个列与标量相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将数据框给定列的每个元素与标量相乘? (我曾尝试过寻找SO,但似乎找不到正确的解决方案)
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)
做类似的事情:
df['quantity'] *= -1 # trying to multiply each row's quantity column with -1
给我一个警告:
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
编辑:
我正在运行0.16.2
熊猫
完整跟踪:
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
推荐答案
经过一番研究后,答案如下:
Here's the answer after a bit of research:
df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning
这篇关于Python:Pandas Dataframe如何将整个列与标量相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文