pandas dataframe duplicate each row 5 times while changing one column

137 Views Asked by At

I have the dataframe:

vid_fn  V1  V2  V3
 a.avi  1   4   5 
 b.avi  7   8   1

I want to change duplicate each row 5 times, while changing the first column:

frame_fn  V1  V2  V3
 a1.jpg  1   4   5 
 a2.jpg  1   4   5 
 a3.jpg  1   4   5 
 a4.jpg  1   4   5 
 a5.jpg  1   4   5 
 b1.jpg  7   8   1 
 b2.jpg  7   8   1 
 b3.jpg  7   8   1 
 b4.jpg  7   8   1 
 b5.jpg  7   8   1 

the 5 values are generate by an outer function, so when calling

my_func(a.avi) 

I get:

[a1.jpg, a2.jpg, a3.jpg, a4.jpg, a5.jpg]

What is the best way to do so?

1

There are 1 best solutions below

0
On BEST ANSWER

You can map the function my_func over vid_fn then explode the dataframe on vid_fn:

df.assign(vid_fn=df['vid_fn'].map(my_func)).explode('vid_fn')\
  .rename(columns={'vid_fn': 'frame_fn'}).reset_index(drop=True)

  frame_fn  V1  V2  V3
0   a1.avi   1   4   5
1   a2.avi   1   4   5
2   a3.avi   1   4   5
3   a4.avi   1   4   5
4   a5.avi   1   4   5
5   b1.avi   7   8   1
6   b2.avi   7   8   1
7   b3.avi   7   8   1
8   b4.avi   7   8   1
9   b5.avi   7   8   1