Home > Mobile >  Pandas Can i duplicate rows and add a column with the values of a list?
Pandas Can i duplicate rows and add a column with the values of a list?

Time:07-26

I have a dataframe like this:

    ID value  repeat  ratio
  0 0  IDx10     6       0.5   
  1 1  IDx11     7       1.5   
  2 2  IDx12     8       2.5   

and i have a list like this: l = [1,2]

What i want to do is to duplicate every row the number of times of the length of the list and in every new row put each value of the list.

And getting a dataframe like this:

    ID value  repeat  ratio  value
  0  0  IDx10  6       0.5    1
  1  0  IDx10  6       0.5    2
  2  1  IDx11  7       1.5    1 
  3  1  IDx11  7       1.5    2  
  4  2  IDx12  8       2.5    1  
  5  2  IDx12  8       2.5    2 

CodePudding user response:

Let us do a cross merge:

out = df.merge(pd.Series(l, name='value2'), how='cross')

output:

   ID  value  repeat  ratio  value2
0   0  IDx12       6    0.5       1
1   0  IDx12       6    0.5       2
2   0  IDx12       6    0.5       3
3   1  IDx12       7    1.5       1
4   1  IDx12       7    1.5       2
5   1  IDx12       7    1.5       3
6   2  IDx12       8    2.5       1
7   2  IDx12       8    2.5       2
8   2  IDx12       8    2.5       3

CodePudding user response:

You can use numpy.repeat , numpy.tile and pandas.assign.

l = [1,2,3]
df = pd.DataFrame(np.repeat(df.values, len(l), axis=0), 
             columns=df.columns).assign(new_val=np.tile(l,len(l)))
print(df)

  ID  value repeat ratio  new_val
0  0  IDx12      6   0.5        1
1  0  IDx12      6   0.5        2
2  0  IDx12      6   0.5        3
3  1  IDx12      7   1.5        1
4  1  IDx12      7   1.5        2
5  1  IDx12      7   1.5        3
6  2  IDx12      8   2.5        1
7  2  IDx12      8   2.5        2
8  2  IDx12      8   2.5        3

  • Related