'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
Solution 1:[1]
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
Solution 2:[2]
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)
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | anky |
Solution 2 | |
Solution 3 | kush |