1

I have the following data frame:

Data Frame:

id animal
1  dog
2  cat
3  rabbit
4  horse
5  fox

I want to replicate each id 3 times. How can I do this in pandas using method chaining?

Expected output:

id animal
1  dog
1  dog
1  dog
2  cat
2  cat
2  cat
3  rabbit
3  rabbit
3  rabbit
4  horse
4  horse
4  horse
5  fox
5  fox
5  fox
Eisen
  • 1,697
  • 9
  • 27
  • Does this answer your question? [How can I replicate rows of a Pandas DataFrame?](https://stackoverflow.com/questions/50788508/how-can-i-replicate-rows-of-a-pandas-dataframe) – wjandrea Feb 24 '23 at 20:20

2 Answers2

2

You can use loc or pipe to chain your duplication:

df.loc[lambda d: d.index.repeat(3)]

Or:

df.pipe(lambda d: d.loc[d.index.repeat(3)])

Output:


   id  animal
0   1     dog
0   1     dog
0   1     dog
1   2     cat
1   2     cat
1   2     cat
2   3  rabbit
2   3  rabbit
2   3  rabbit
3   4   horse
3   4   horse
3   4   horse
4   5     fox
4   5     fox
4   5     fox
mozway
  • 194,879
  • 13
  • 39
  • 75
1

One way is to use pandas.reindex:

df.reindex(df.index.repeat(3)).reset_index(drop=True)

or

df.set_index('id').reindex(df['id'].repeat(3)).reset_index()

Output:

    id  animal
0    1     dog
1    1     dog
2    1     dog
3    2     cat
4    2     cat
5    2     cat
6    3  rabbit
7    3  rabbit
8    3  rabbit
9    4   horse
10   4   horse
11   4   horse
12   5     fox
13   5     fox
14   5     fox
SomeDude
  • 13,876
  • 5
  • 21
  • 44