Python Forum
Selecting rows that contain certain values using two alternatives
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Selecting rows that contain certain values using two alternatives
Hi guys,

I have a dataset and the following code:

a = dataset.set_index('c', append=True).sort_index()
This generates a table with 3 indices (a, b and c) and one column containing values.

The column c includes a couple of characteristics of which I only want to select the rows with "Total".

Therefore, I have used:

dataset.loc[('Total'), :]
However, this generates a KeyError: 'Total'

Alternatively, the code works using the following:

dataset.set_index('c', append=True).sort_index().loc[(slice(None), slice(None), 'Total'), :]
To me it is not clear why it works with the second alternative but not with the first one.

I would be happy if someone could please help me.

Many thanks!
Maybe you're thinking of .xs?

import pandas as pd

if __name__ == "__main__":
    dataset = pd.DataFrame([(1,1,'a',10),(2,2,'b',20),(3,3,'c',30),
    dataset.set_index(["a","b","c"], inplace=True)

Possibly Related Threads…
Thread Author Replies Views Last Post
  Selecting the first occurrence of a duplicate knight2000 8 590 May-25-2021, 01:37 AM
Last Post: knight2000
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 245 May-04-2021, 10:51 PM
Last Post: rhat398
  Eliminating error in Python update-alternatives Led_Zeppelin 2 466 Apr-14-2021, 12:49 PM
Last Post: Led_Zeppelin
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 1,162 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  How to generate rows based on values in a column to fill missing values codesmatter 1 478 Oct-31-2020, 12:05 AM
Last Post: Larz60+
  Dropping rows with missing values NewBeie 2 677 Jul-27-2020, 06:29 AM
Last Post: NewBeie
  Find only the rows containing null values Bhavika 2 631 Jun-10-2020, 01:25 PM
Last Post: Bhavika
  Selecting text as an input lazerwolf101 2 613 May-29-2020, 06:52 AM
Last Post: lazerwolf101
  Are there any python alternatives for LuaMacros? NathanStanley 1 1,412 Apr-07-2020, 09:51 AM
Last Post: Larz60+
  Do Calculation between Rows based on Column values - Pandas Dataframe ahmedwaqas92 0 1,013 Jan-28-2020, 07:06 AM
Last Post: ahmedwaqas92

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020