Home > Software engineering >  How replace a row in a dataframe with a subset of that dataframe
How replace a row in a dataframe with a subset of that dataframe

Time:06-05

I have a dataframe like this:

df1

     Category  Type    Dependent-Category
 0    1         O       A                  <---- Replace this row
 1    1         O       24
 2    1         O       5
 3    1         Y       14
 4    A         Y       10
 5    A         O       2
 6    A         O       9

I want to replace row 0, with all the rows where Category == A. Final df should look like this

df_final

     Category  Type    Dependent-Category
 0    A         Y       10
 1    A         O       2
 2    A         O       9
 3    1         O       24
 4    1         O       5
 5    1         Y       14
 6    A         Y       10
 7    A         O       2
 8    A         O       9

CodePudding user response:

Let us do it step by step

sub = df.loc[df.Category=='A']
torep = df.loc[df['Dependent-Category']=='A']
sub.index = torep.index.repeat(len(sub.index))

out = pd.concat([df.drop(torep.index),sub]).sort_index()
  Category Type Dependent-Category
0        A    Y                 10
0        A    O                  2
0        A    O                  9
1        1    O                 24
2        1    O                  5
3        1    Y                 14
4        A    Y                 10
5        A    O                  2
6        A    O                  9
  • Related