2021年2月2日星期二

Python Pandas .loc using a different dataframe

I'm trying to assign dataframe columns to the row and column of the .loc function. I have a dataframe df with no set index, with Sites and Visits as my column headers

Index Site Visit
0 101 Visit 1
1 102 Visit 1
2 102 Visit 2

I have another dataframe df2 with Sites as my dataframe index, and Visits as my columns with Cost as my values.

Index Visit 1 Visit 2
101 50 60
102 100 120

I'm trying to use .loc to index the Cost from df2 and add it as a column to df1 like so

Index Site Visit Cost
0 101 Visit 1 50
1 102 Visit 1 60
2 102 Visit 2 120

I tried using the following code to provide a row and column value

df['Cost'] = df2.loc[df['Site'],df['Visit']]  

But i got the following error:

KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported.   The following labels were missing: etc. etc.   

Any idea how to use two column values from one dataframe as the .loc row and column values?

Thanks so much for your help!

https://stackoverflow.com/questions/66020134/python-pandas-loc-using-a-different-dataframe February 03, 2021 at 09:47AM

没有评论:

发表评论