Home > database >  how to add new input row on dataframe?
how to add new input row on dataframe?

Time:01-12

I have this data-frame

df = pd.DataFrame({'Type':['A','A','B','B'], 'Variants':['A3','A6','Bxy','Byz']})

it shows like this

Type    Variants
0   A   A3
1   A   A6
2   B   Bxy
3   B   Byz

I should make a function that adds a new row below each on every new Type key-values. it should go like this if I'm adding n=2

Type    Variants
0   A   A3
1   A   A6
2   A   Nan
3   A   Nan
4   B   Bxy
5   B   Byz
6   B   Nan
7   B   Nan

can anyone help me with this , I will appreciate it a lot, thx in advance

CodePudding user response:

Create a dataframe to merge with your original one:

def add_rows(df, n):
    df1 = pd.DataFrame(np.repeat(df['Type'].unique(), n), columns=['Type'])
    return pd.concat([df, df1]).sort_values('Type').reset_index(drop=True)

out = add_rows(df, 2)
print(out)

# Output
  Type Variants
0    A       A3
1    A       A6
2    A      NaN
3    A      NaN
4    B      Bxy
5    B      Byz
6    B      NaN
7    B      NaN
  •  Tags:  
  • Related