Python:Pandas Dataframe 如何将整列与标量相乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33768122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:56:55  来源:igfitidea点击:

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

pythonpandaschained-assignment

提问by labheshr

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)

如何将数据帧给定列的每个元素与标量相乘?(我曾尝试寻找 SO,但似乎无法找到正确的解决方案)

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.2of Pandas

我在跑0.16.2熊猫

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

采纳答案by labheshr

Here's the answer after a bit of research:

这是经过一番研究后的答案:

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

回答by GiannisIordanou

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

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

回答by maswadkar

try using apply function.

尝试使用应用功能。

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

回答by Rglish

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

有点旧,但我仍然得到相同的 SettingWithCopyWarning。这是我的解决方案:

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

回答by DJK

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

注意:对于那些使用 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

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

回答by Michael Rice

I got this warning using Pandas 0.22. You can avoid this by being veryexplicit using the assignmethod:

我使用 Pandas 0.22 收到此警告。您可以通过使用assign方法非常明确地避免这种情况:

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

回答by stephenb

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

最近的熊猫版本具有 pd.DataFrame.multiply 功能。

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

回答by Hyman Fleeting

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

游戏有点晚了,但对于未来的搜索者来说,这也应该有效:

df.quantity = df.quantity  * -1

回答by DINA TAKLIT

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.

这会将索引为 6 的列与 -1 相乘。

回答by Sarah

The real problem of why you are getting the error is not that there is anything wrong with your code: you can use either iloc, loc, or apply, or *=, another of them could have worked.

为什么会出现错误的真正问题不在于您的代码有什么问题:您可以使用iloc, loc, or apply, or *=,其中另一个可以工作。

The real problem that you have is due to how you created the df DataFrame. Most likely you created your df as a slice of another DataFrame without using .copy().The correct way to create your df as a slice of another DataFrame is df = original_df.loc[some slicing].copy().

您遇到的真正问题在于您如何创建 df DataFrame。很可能您将 df 创建为另一个 DataFrame 的一个切片,而没有使用.copy().将 df 创建为另一个 DataFrame 的一个切片的正确方法是df = original_df.loc[some slicing].copy().

The problem is already stated in the error message you got " 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"
You will get the same message in the most current version of pandas too.

该问题已在您收到的错误消息中说明:“ SettingWithCopyWarning: 正在尝试在 DataFrame 的切片副本上设置值。尝试使用 .loc[row_indexer,col_indexer] = value 代替”
您将收到相同的消息在最新版本的熊猫中也是如此。

Whenever you receive this kind of error message, you should always check how you created your DataFrame. Chances are you forgot the .copy()

每当您收到此类错误消息时,您应该始终检查您创建 DataFrame 的方式。你可能忘记了.copy()