pandas 将数据帧的特定列乘以常数标量值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35094256/
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-09-14 00:35:18  来源:igfitidea点击:

Multiplying specific columns of dataframe by constant scalar value

pythonpandasdataframemultiplying

提问by Korean_Of_the_Mountain

How do I multiply only specific columns of a dataframe by a constant value?

如何仅将数据帧的特定列乘以常数值?

df0 = pd.DataFrame({'A' : 1.,
                    'B' : 1,
                    'C' : 1,
                    'D' : np.array([1] * 4,dtype='int32')})

mult_by_two = df0.iloc[:,2:].mul(2)
print mult_by_two

I get this:

我明白了:

   C  D
0  2  2
1  2  2
2  2  2
3  2  2

but what I want is this:

但我想要的是:

   A  B  C  D
0  1  1  2  2
1  1  1  2  2
2  1  1  2  2
3  1  1  2  2

回答by Mike Müller

You can assign the result to df0:

您可以将结果分配给df0

>>> df0.iloc[:,2:] = df0.iloc[:,2:].mul(2)
>>> df0

   A  B  C  D
0  1  1  2  2
1  1  1  2  2
2  1  1  2  2
3  1  1  2  2

If you want a copy, make before the assigment:

如果您想要副本,请在分配之前制作:

df1 = df0.copy()
df1.iloc[:,2:] = df1.iloc[:,2:].mul(2)

回答by Anton Protopopov

If you need to multiply on scalar you don't need to call mulmethod you could use usual *operator:

如果您需要乘以标量,则不需要调用mul方法,您可以使用通常的*运算符:

In [24]: df0.iloc[:,2:] * 2
Out[24]: 
   C  D
0  2  2
1  2  2
2  2  2
3  2  2

For your question you could use pd.concatwith your first columns and columns you are multiplying:

对于您的问题,您可以pd.concat将第一列和要相乘的列一起使用:

In [25]: pd.concat([df0.iloc[:,:2], df0.iloc[:,2:] * 2], axis=1)
Out[25]: 
   A  B  C  D
0  1  1  2  2
1  1  1  2  2
2  1  1  2  2
3  1  1  2  2