Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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    
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading