简体   繁体   中英

How to multiple all rows of a Pandas dataframe by a single row in another Pandas dataframe?

I have this Dataframe in pythondf1

and I want to multiple every row in the first dataframe by this single row in the dataframe below as a vectordf2

Some things I have tried from googling : df.mul, df.apply. But it seems to multiply the two frames together normally instead of a vectorized operation

Example data:

df = pd.DataFrame({'x':[1,2,3], 'y':[1,2,3]})
v1 = pd.DataFrame({'x':[2], 'y':[3]})

Multiply DataFrame with row:

df.multiply(np.array(v1), axis='columns')

If the use case needs accurate matching of columns

Example:

df = pd.DataFrame([[1, 2], [3, 4]], columns=['x', 'y'])
coeffs_df = pd.DataFrame([[10, 9]], columns=['y', 'x'])

Need to convert the df with single row ( coeffs_df ) to a series first, the perform multiply

df.multiply(coeffs_df.iloc[0], axis='columns')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM