3

I have a dataframe with 142 rows. I have created a new column. I want to fill this new column with a list containing strings.

my_list = ['abc','def','hig']
df['names'] = df['names'].fill(my_list) #pseudo code

I want to fill all the 142 rows in 'names' column with string values in the list in the same order.

The output should be as:   

     names
   1 abc
   2 def
   3 hig
   4 abc
   5 def
7
  • you want all 142 rows filled with this list? so df['names']=[['abc','def','hig']]*len(df) ? Commented Jan 20, 2020 at 16:33
  • I think so @anky_91 Commented Jan 20, 2020 at 16:35
  • have you tried df['names'] = list ? Commented Jan 20, 2020 at 16:35
  • I mean with string values inside the list.first value in the list should be assigned to first row,second value to second row and so on. Commented Jan 20, 2020 at 16:36
  • 1
    Sidenote, try to avoid using reserved names for your variable, don,t use list, instead something like my_list. Commented Jan 20, 2020 at 16:47

3 Answers 3

7

I think you need something like below withh np.resize which will resize the list according to the dataframe.

Example dataframe:

df = pd.DataFrame(np.random.randint(0,100,size=(5,4)),columns=list('ABCD'))

    A   B   C   D
0  10  99   0  61
1  55   0  52  53
2  34  88  79  54
3  25  32   1  89
4  39  30  77   5

Solution:

mylist=['abc','def','hig']
df['names'] = np.resize(mylist,len(df))
print(df)

    A   B   C   D names
0  10  99   0  61   abc
1  55   0  52  53   def
2  34  88  79  54   hig
3  25  32   1  89   abc
4  39  30  77   5   def
Sign up to request clarification or add additional context in comments.

Comments

3

You almost had it. Try this,

import pandas as pd
list = ['abc','def','hig']
df=pd.DataFrame(list)
df.columns=['names'] #provides a name for the column

df_repeated = pd.concat([df]*48, ignore_index=True)

which gives you 48*3=144 rows. Then,

df_repeated =df_repeated.reindex(df_repeated.index.drop(144)).reset_index(drop=True)

1 Comment

ahhh. Ok, let me think on it.
2

just assign the list to the column like so; it will simultaneously create the column called 'names' and fill it with the list :

df['names'] = my_list

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.