0

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

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?

SeanK22
  • 163
  • 8
  • just use `numpy` for this: `np.repeat(df.Weight.to_numpy(), df.Wheels)`. Then you can put that array into a Series or DataFrame if you really want. Since this new column has a totally different shape than the original DataFrame, it doesn't make sense to store the repeated data in the same object as the original. – ALollz Jan 05 '22 at 19:20
  • 1
    Please have a look at [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and [edit] to include your sample input and expected output as text, not as an image or link, to make a [mcve] – G. Anderson Jan 05 '22 at 19:20

2 Answers2

2

Assuming you have a pandas dataframe named df.

import numpy as np
np.repeat(df['weigth'], df['wheels'])
mozway
  • 194,879
  • 13
  • 39
  • 75
2

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
Corralien
  • 109,409
  • 8
  • 28
  • 52