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

Trying to replicate a particular row in a pandas dataframe

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].

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 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

>Solution :

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
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