简体   繁体   中英

how to fill a Pandas dataframe column with a list containing string values

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

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM