0

I have a dataframe which is multi-index and passing a list or a string to the loc accessor doesn't work.

My dataframe has two indexes : Name_1, Name_2.

Let tempList=[ 'Marco John' , Peter Dorset']

data.loc['Marco John','Peter Dorset']['Combined Salary'] works

data.loc[tempList[0],tempList[1]]['Combined Salary'] works

data.loc[tempList]['Combined Salary'] doesn't work?

tempstring = tempList[0]+','+templist[1]

data.loc[tempstring]['Combined Salary'] 

doesn't work?

Can anyone tell me what's wrong with passing a string to the loc accessor?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
KBS
  • 1
  • 1
  • Please share sample for your dataframe. The value in .loc[row_indexer, column_indexer], you can pass any two values for row_indexer or column_indexer. It doesn't accept a string or list. – Anant Kumar Aug 03 '20 at 14:01

1 Answers1

0

The following code results in an indexer equal to "Marco John,Peter Dorset"; which is a format not acceptable by pandas

tempstring = tempList[0]+','+templist[1]
data.loc[tempstring]['Combined Salary']

Did you try the following?

data.loc[*tempList]['Combined Salary']

The * operator before tempList should unpack the list

Hussein Fawzy
  • 366
  • 2
  • 16
  • No it doesn't work data.loc[*tempList]['Combined Salary'] returns a syntax error. I have checked the version of python I am using and it is 3.7.4 – KBS Aug 03 '20 at 14:17