问题
I am trying to multiply a 10X7 Pandas dataframe by a 1X7 dataframe in Python.
Here is what I have:
df = pd.DataFrame(np.random.rand(10,7),columns=list('ABCDEFG'))
df_1 = pd.DataFrame(np.random.rand(1,7),columns=list('ABCDEFG'))
I tried this:
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
I need to multiply all rows of df by df_1.
I need:
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
Is there a simple way to achieve this multiplication this in Python?
回答1:
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
回答2:
like this:
%%timeit
df.mul(df_1.ix[0])
1000 loops, best of 3: 251 µs per loop
check results match:
all(df.mul(df_1.ix[0]) == df.apply(lambda x: x * df_1.ix[0],axis = 1))
True
This avoids apply. Link to docs
来源:https://stackoverflow.com/questions/30563934/python-pandas-n-x-m-dataframe-multiplied-by-1-x-m-dataframe