1

I have a pandas dataframe like so:

col1 col2 col3
 1    8    6
 2    9    5
 5    3    9

Now I want to add a new column with values from a list for each and every row of my dataframe. So if my list is like so:

lst = ["a", "b","c"]

then I want the final dataframe to be like:

col1 col2 col3 name
 1    8    6    a
 1    8    6    b
 1    8    6    c
 2    9    5    a
 2    9    5    b
 2    9    5    c
 5    3    9    a
 5    3    9    b
 5    3    9    c

1 Answer 1

1

First idea is use Index.repeat by length of list and then append new column with numpy.tile:

lst = ["a", "b","c"]

df1 = (df.loc[df.index.repeat(len(lst))]
             .assign(name=np.tile(lst, len(df)))
             .reset_index(drop=True))
print (df1)
   col1  col2  col3 name
0     1     8     6    a
1     1     8     6    b
2     1     8     6    c
3     2     9     5    a
4     2     9     5    b
5     2     9     5    c
6     5     3     9    a
7     5     3     9    b
8     5     3     9    c

Or use cross join with DataFrame from list:

df1 = df.assign(a=1).merge(pd.DataFrame({'name':lst, 'a':1}), on='a').drop('a', axis=1)
print (df1)
   col1  col2  col3 name
0     1     8     6    a
1     1     8     6    b
2     1     8     6    c
3     2     9     5    a
4     2     9     5    b
5     2     9     5    c
6     5     3     9    a
7     5     3     9    b
8     5     3     9    c
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.