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

时间:2016-01-29 21:20:35

标签: python pandas dataframe multiplying

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

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

我明白了:

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

但我想要的是:

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

2 个答案:

答案 0 :(得分:4)

您可以将结果分配给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

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

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

答案 1 :(得分:0)

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

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

对于您的问题,您可以将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
相关问题