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?
CodePudding user response:
If length of list is same like count of True
s 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