Python Pandas-n X m数据框乘以1 X m数据框 [英] Python Pandas - n X m DataFrame multiplied by 1 X m Dataframe

查看:205
本文介绍了Python Pandas-n X m数据框乘以1 X m数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Python的10X7熊猫数据帧乘以1X7数据帧.

I am trying to multiply a 10X7 Pandas dataframe by a 1X7 dataframe in Python.

这就是我所拥有的:

df = pd.DataFrame(np.random.rand(10,7),columns=list('ABCDEFG'))
df_1 = pd.DataFrame(np.random.rand(1,7),columns=list('ABCDEFG'))

我尝试过:

df_prod = pd.DataFrame(columns=df)
for i in range(0, df.shape[0]):
    df_prod.iloc[i,:] = df[i,:].tolist()*df_1.iloc[0,:].tolist()

但是我收到此错误消息:

But I get this error message:

Traceback (most recent call last):
  File "C:\Python27\test.py", line 29, in <module>
    df_elem.iloc[i,:] = df_val[i,:].tolist()*df_cf.iloc[0,:].tolist()
  File "C:\python27\lib\site-packages\pandas\core\frame.py", line 1678, in __getitem__
    return self._getitem_column(key)
  File "C:\python27\lib\site-packages\pandas\core\frame.py", line 1685, in _getitem_column
    return self._get_item_cache(key)
  File "C:\python27\lib\site-packages\pandas\core\generic.py", line 1050, in _get_item_cache
    res = cache.get(item)
TypeError: unhashable type

我需要将df的所有行乘以df_1.

I need to multiply all rows of df by df_1.

我需要:

df.iloc[0,:] * df_1
df.iloc[1,:] * df_1
df.iloc[2,:] * df_1
df.iloc[3,:] * df_1
.
.
.
.
df.iloc[9,:] * df_1

有没有简单的方法可以在Python中实现这种乘法?

Is there a simple way to achieve this multiplication this in Python?

推荐答案

如果要逐行进行乘法,可以尝试以下操作:

If you want to do the multiplication row-wise you could try this:

%timeit df_prod = df.apply(lambda x: x * df_1.ix[0],axis = 1)
100 loops, best of 3: 6.21 ms per loop

但是按列进行乘法会更快:

however it will be much faster to do the multiplication column-wise:

%timeit = df_prod = pd.DataFrame({c:df[c]* df_1[c].ix[0] for c in df.columns})
100 loops, best of 3: 2.4 ms per loop

这篇关于Python Pandas-n X m数据框乘以1 X m数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆