本文介绍了 pandas :两个数据帧的元素乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我知道如何在两个Pandas数据帧之间进行元素乘法运算。然而,当两个数据帧的尺寸不兼容时,事情变得更加复杂。例如下面 df * df2 是简单的,但 df * df3 是一个问题:

  df = pd.DataFrame({'col1':[1.0] * 5,
'col2':[2.0] * 5,
'col3':[3.0] * 5},index = range(1,6),)
df2 = pd.DataFrame({'col1':[10.0] * 5,
'col2 ':[100.0] * 5,
'col3':[1000.0] * 5},index = range(1,6),)
df3 = pd.DataFrame({'col1':[0.1 ] * 5},index = range(1,6),)

df.mul(df2,1)#元素乘子没有问题

df.mul df3,1)#df(row * col)不等于df3(row * col)
col1 col2 col3
1 0.1 NaN NaN
2 0.1 NaN NaN
3 0.1 NaN NaN
4 0.1 NaN NaN
5 0.1 NaN NaN

在上述情况,如何将df的每一列与df3.col1 相乘?



我的尝试: / strong>我试图复制 df3.col1 len(df.columns.values)次以获取数据帧与 df 相同的维度:

  df3 = pd.DataFrame ([df3.col1 for n in range(len(df.columns.values))])
df3
1 2 3 4 5
col1 0.1 0.1 0.1 0.1 0.1
col1 0.1 0.1 0.1 0.1 0.1
col1 0.1 0.1 0.1 0.1 0.1

但这会创建一个数据框尺寸3 * 5,而我在5 * 3之后。我知道我可以用 df3.T()取代转置,以获得我需要的,但我认为这不是最快的方式。

解决方案
 在[161]中:pd.DataFrame(df.values * df2.values,columns = df.columns,index = df.index)
出[161]:
col1 col2 col3
1 10 200 3000
2 10 200 3000
3 10 200 3000
4 10 200 3000
5 10 200 3000


I know how to do element by element multiplication between two Pandas dataframes. However, things get more complicated when the dimensions of the two dataframes are not compatible. For instance below df * df2 is straightforward, but df * df3 is a problem:

df = pd.DataFrame({'col1' : [1.0] * 5,
                   'col2' : [2.0] * 5,
                   'col3' : [3.0] * 5 }, index = range(1,6),)
df2 = pd.DataFrame({'col1' : [10.0] * 5,
                    'col2' : [100.0] * 5,
                    'col3' : [1000.0] * 5 }, index = range(1,6),)
df3 = pd.DataFrame({'col1' : [0.1] * 5}, index = range(1,6),)

df.mul(df2, 1) # element by element multiplication no problems

df.mul(df3, 1) # df(row*col) is not equal to df3(row*col)
   col1  col2  col3
1   0.1   NaN   NaN
2   0.1   NaN   NaN
3   0.1   NaN   NaN
4   0.1   NaN   NaN
5   0.1   NaN   NaN

In the above situation, how can I multiply every column of df with df3.col1?

My attempt: I tried to replicate df3.col1 len(df.columns.values) times to get a dataframe that is of the same dimension as df:

df3 = pd.DataFrame([df3.col1 for n in range(len(df.columns.values)) ])
df3
        1    2    3    4    5
col1  0.1  0.1  0.1  0.1  0.1
col1  0.1  0.1  0.1  0.1  0.1
col1  0.1  0.1  0.1  0.1  0.1

But this creates a dataframe of dimensions 3 * 5, whereas I am after 5*3. I know I can take the transpose with df3.T() to get what I need but I think this is not that the fastest way.

解决方案
In [161]: pd.DataFrame(df.values*df2.values, columns=df.columns, index=df.index)
Out[161]:
   col1  col2  col3
1    10   200  3000
2    10   200  3000
3    10   200  3000
4    10   200  3000
5    10   200  3000

这篇关于 pandas :两个数据帧的元素乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:42