0

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?

1 Answer 1

5

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)
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.