I have a list of names of columns (cols) that exist in one dataframe.
I want to insert columns by those names in another dataframe.
So I am using a for loop to iterate the list and create the columns one by one:
cols = ['DEPTID', 'ACCOUNT', 'JRNL LINE DESCRIPTION', 'JRNL DATE', 'BASE AMOUNT', 'FOREIGN CURRENCY', 'FOREIGN AMOUNT', 'JRNL SOURCE']
for col in cols:
# "summary" and "obiee" are dataframes
summary.loc[obiee['mapid'], col] = obiee[col].tolist()
I would like to get rid of the for loop, however.
So I have tried multiple column assignment using the .loc syntax:
cols = ['DEPTID', 'ACCOUNT', 'JRNL LINE DESCRIPTION', 'JRNL DATE', 'BASE AMOUNT', 'FOREIGN CURRENCY', 'FOREIGN AMOUNT', 'JRNL SOURCE']
summary.loc[obiee['mapid'], cols] = obiee[cols]
but Pandas will throw an error:
KeyError: "['DEPTID' 'ACCOUNT' 'JRNL LINE DESCRIPTION' 'JRNL DATE' 'BASE AMOUNT'\n 'FOREIGN CURRENCY' 'FOREIGN AMOUNT' 'JRNL SOURCE'] not in index"
Is it not possible with this syntax? How can I do this otherwise?
.locapproach. pandas.pydata.org/pandas-docs/stable/reference/api/… says it is label based so those columns must be there. What you could do is just pre-allocate those columns and you're good.for col in cols: summary[col] = Noneor you can use theassignproperty. As long as the columns exist you should be able to use.locmerge,concatorjoindata frames.