Python Pandas - n X m DataFrame multiplied by 1 X m Dataframe -
i trying multiply 10x7 pandas dataframe 1x7 dataframe in python.
here 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) in range(0, df.shape[0]): df_prod.iloc[i,:] = df[i,:].tolist()*df_1.iloc[0,:].tolist()
but 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 multiply rows of df
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 simple way achieve multiplication in python?
if want multiplication row-wise 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 faster multiplication column-wise:
%timeit = df_prod = pd.dataframe({c:df[c]* df_1[c].ix[0] c in df.columns}) 100 loops, best of 3: 2.4 ms per loop
Comments
Post a Comment