How to Add a Column Based on a Boolean List in Pandas?

Question:

I have a DataFrame and a list like this:

df = pd.DataFrame({'bool':[True,False,True,False, False]})
lst = ["aa","bb"]

Now I want to add the list as a column to the DataFrame based on boolean values like this:

df = pd.DataFrame({'bool':[True,False,True,False, False], 'lst':['aa','','bb','','']})

My solution is

df1 = df[df['bool'] == True].copy()
df2 = df[df['bool'] == False].copy()
df1['lst'] = lst
df2['lst'] = ''
df = pd.concat([df1, df2])

But it created so many DataFrames. Is there a better way to do this?

Asked By: David

||

Answers:

If length of list is same like count of Trues values use:

df.loc[df['bool'], 'lst'] = lst
df['lst'] = df['lst'].fillna('')
print (df)
    bool lst
0   True  aa
1  False    
2   True  bb
3  False    
4  False    
    
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.