2

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.