2015-11-17 23 views
23

如何将数据帧的给定列的每个元素与标量相乘? (我试图寻找对SO,但似乎无法找到合适的解决方案)Python:Pandas Dataframe如何将整列与标量相乘

做这样的事情:

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 

注:如果可能的话,我不想迭代数据框并做这样的事情......因为我认为在整个列上的任何标准数学运算都可能不必编写循环:

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 
+0

使用'dtype'检查该列的类型。我无法复制那个错误,给予完整的回溯也是很好的。 – Leb

+0

我已编辑添加完整的跟踪...也没有错误,它的警告(为了清晰) – labheshr

+0

我认为这是由该行以外的东西造成的,或者该行导致警告升高从早期产生。你得到的东西与切片数据帧有关。 – Leb

回答

28

这里有一点研究后回答:

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

这引发了熊猫0.18中的SettingWithCopyWarning。 0。 – kadrach

0

尝试df['quantity'] = df['quantity'] * -1

+0

这与df ['quantity'] * = -1没有什么区别(是的,我得到了同样的警告) – labheshr

23

尝试使用应用函数。

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

与循环相比,这是相当优美的,虽然我仍然得到SettingWithCopyWarning – labheshr

2

有点老了,但我仍然得到同样的SettingWithCopyWarning。这里是我的解决办法:

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

注:使用熊猫0.20.3,和那些正在寻找一个答案,所有这些选项都将工作

df = pd.DataFrame(np.ones((5,4)),columns=['one','two','three','four']) 

df.one*=5 
df.two = df.two*5 
df.three = df.three.multiply(5) 
df['four'] = df['four']*5 

导致

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