Home > front end >  Trying to replicate a particular row in a pandas dataframe
Trying to replicate a particular row in a pandas dataframe

Time:10-23

I am trying to duplicate a value at a particular indexed row and insert this new duplicated row below the original row in the dataframe.

I have the following code:

indexnumber = random.randrange(datafile.shape[0])
newdf = pd.DataFrame(np.repeat(datafile.iloc[indexnumber].values, 2, axis=0))
print(newdf)

I want to randomly pick one reaction time and duplicate it, next to the original item, so that if the list is [2,3,4] and the random number is 1, the resulting list should be [2,3,3,4].

I would be so grateful for any help!

The first 10 rows of the Datafile dataframe:

print(datafile.head(10))
     0
0  307
1  209
2  371
3  266
4  372
5  298
6  338
7  302
8  264
9  247

CodePudding user response:

You can use Index.repeat with a custom array as repeater:

# set up repeater array with 1s
n = np.ones(len(df))
# pick one random value to be 2
n[np.random.randint(0, len(df))] = 2

# reindex
out = df.loc[df.index.repeat(n)]

Example output:

     0
0  307
1  209
2  371
3  266  # duplicated
3  266  #
4  372
5  298
6  338
7  302
8  264
9  247
  • Related