Reputation: 7644
i have a dataframe df with 1 row and 20 columns:
id name age...... And so on
1 Ian 29......
I also have a list L
L = ['Doctor', 'Carpenter']
I want to create a column 'Occupation'
in my dataframe such that, all the other column values remain same.
Final output required:
id name age...... Occupation
1 Ian 29...... Doctor
1 Ian 29...... Carpenter
I was trying to iterate the list and then use pd.concat to append two slices.
Is there a better way to do it?
Upvotes: 0
Views: 1030
Reputation: 862511
You can repeat index values by length of list and then assign to new column:
L = ['Doctor', 'Carpenter']
df = df.loc[df.index.repeat(len(L))].assign(Occupation = L).reset_index(drop=True)
print (df)
id name age Occupation
0 1 Ian 29 Doctor
1 1 Ian 29 Carpenter
Another idea with first assign nested list and then DataFrame.explode
:
df = df.assign(Occupation = [L]).explode('Occupation').reset_index(drop=True)
Upvotes: 5