David
David

Reputation: 13

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

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?

Upvotes: 1

Views: 241

Answers (1)

jezrael
jezrael

Reputation: 862511

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    
    

Upvotes: 2

Related Questions