如何将数据帧中给定列的每个元素与标量相乘?(我已经尝试过了,但似乎找不到正确的解决方案)
做一些类似的事情:
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
注意:如果可能的话,我不想在数据帧上迭代,也不想做像this...as这样的事情。我认为在整个列上进行任何标准的数学操作都应该是可能的,而不必编写一个循环:
for idx, row in df.iterrows():
df.loc[idx, 'quantity'] *= -1
编辑:
我正在运行0.16.2
of Pandas
完整跟踪:
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
发布于 2015-11-18 12:50:23
以下是经过一些研究后的答案:
df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning
发布于 2015-11-18 10:33:00
尝试使用apply函数。
df['quantity'] = df['quantity'].apply(lambda x: x*-1)
发布于 2017-09-26 23:41:42
注意:对于那些使用pandas 0.20.3和更高版本,并正在寻找答案的人,所有这些选项都将有效:
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
这导致了
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
https://stackoverflow.com/questions/33768122
复制