Home > Software engineering >  Python Pandas Repeat a value x amount of times according to x value
Python Pandas Repeat a value x amount of times according to x value

Time:01-06

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?

CodePudding user response:

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

CodePudding user response:

Assuming you have a pandas dataframe named df.

import numpy as np
np.repeat(df['weigth'], df['wheels'])
  •  Tags:  
  • Related