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

Python Pandas Repeat a value x amount of times according to x value

I am new to Python and Pandas and am trying so have a simple function that will repeat the value x amount of times accoring to a adjacent value.

For example:

enter image description here

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

I want to take the first column (weight) and add it to a new column based on the amount next to it (wheels). So the column will have 1.5 27x, than immediatly after will have 2.4 177x and repeate this for all values shown. Does anyone know a simple way to do this?

>Solution :

Use Series.repeat:

out = df['Weight'].repeat(df['Wheels'])
print(out)

# Output
0    1.5
0    1.5
1    2.4
1    2.4
1    2.4
Name: Weight, dtype: float64

Setup:

df = pd.DataFrame({'Weight': [1.5, 2.4], 'Wheels': [2, 3]})
print(df)

# Output
   Weight  Wheels
0     1.5       2
1     2.4       3
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