Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding duplicate rows to a DataFrame

I did not figure out how to solve the following question! consider the following data set:

df = pd.DataFrame(data=np.array([['a',1, 2, 3], ['a',4, 5, 6],
                                 ['b',7, 8, 9], ['b',10, 11 , 12]]),
 columns=['id','A', 'B', 'C'])

  id   A    B    C
  a    1    2    3
  a    4    5    6
  b    7    8    9
  b    10   11   12

I need to group the data by id and in each group duplicate the first row and add it to the dataset like the following data set:

  id   A    B    C    A  B  C
  a    1    2    3    1  2  3
  a    4    5    6    1  2  3
  b    7    8    9    7  8  9
  b    10   11   12   7  8  9

I really appreciate it for your help.

I did the following steps, however I could not expand it :

df1 = df.loc [0:0 , 'A' :'C']
df3 = pd.concat([df,df1],axis=1)
like image 547
Elham Avatar asked Jun 28 '26 14:06

Elham


2 Answers

Use groupby + first, and then concatenate df with this result:

v = df.groupby('id').transform('first')
pd.concat([df, v], 1)

  id   A   B   C  A  B  C
0  a   1   2   3  1  2  3
1  a   4   5   6  1  2  3
2  b   7   8   9  7  8  9
3  b  10  11  12  7  8  9
like image 162
cs95 Avatar answered Jul 01 '26 03:07

cs95


cumcount + where+ffill

v=df.groupby('id').cumcount()==0

pd.concat([df,df.iloc[:,1:].where(v).ffill()],1)
Out[57]: 
  id   A   B   C  A  B  C
0  a   1   2   3  1  2  3
1  a   4   5   6  1  2  3
2  b   7   8   9  7  8  9
3  b  10  11  12  7  8  9
like image 26
BENY Avatar answered Jul 01 '26 03:07

BENY