Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Structure arrays for broadcasting numpy python

I have a dataframe with is in long-format

import pandas as pd
import numpy as np


df = pd.DataFrame({'col1': [1], 'col2': [10]})

ratio = pd.Series([0.1, 0.70, 0.2])

# Expected Output

df_multiplied = pd.DataFrame({'col1': [0.1, 0.7, 0.2], 'col2': [1, 7, 2]})

My attempt was to convert it into numpy arrays and use np.tile

np.tile(df.T.values, len(df_ratio) * np.array(df_ratio).T

Is there any better way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

Repeat the row n times where n is the ratio series’ length, then multiple along row axis by the ratio series:

>>> pd.concat([df]*ratio.shape[0], ignore_index=True).mul(ratio, axis='rows')

   col1  col2
0   0.1   1.0
1   0.7   7.0
2   0.2   2.0

Or, you can implement similar logic with numpy, repeat the array n times then multiply by ratio values with expanded dimension:

>>> np.repeat([df.values], ratio.shape[0], axis=1)*ratio.values[:,None]

array([[[0.1, 1. ],
        [0.7, 7. ],
        [0.2, 2. ]]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading