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
#1
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!
Reply
#2
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),
        (4,4,"Total",40)],
        columns=["a","b","c","value"])
    dataset.set_index(["a","b","c"], inplace=True)
    dataset.xs("Total",level="c",drop_level=False)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,599 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  Calculate next rows based on previous values of array divon 0 1,716 Nov-23-2021, 04:44 AM
Last Post: divon
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,080 May-04-2021, 10:51 PM
Last Post: rhat398
  Eliminating error in Python update-alternatives Led_Zeppelin 2 2,942 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 6,957 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 2,093 Oct-31-2020, 12:05 AM
Last Post: Larz60+
  Dropping rows with missing values NewBeie 2 2,325 Jul-27-2020, 06:29 AM
Last Post: NewBeie
  Find only the rows containing null values Bhavika 2 2,403 Jun-10-2020, 01:25 PM
Last Post: Bhavika
  Are there any python alternatives for LuaMacros? NathanStanley 1 3,741 Apr-07-2020, 09:51 AM
Last Post: Larz60+
  Do Calculation between Rows based on Column values - Pandas Dataframe ahmedwaqas92 0 2,110 Jan-28-2020, 07:06 AM
Last Post: ahmedwaqas92

Forum Jump:

User Panel Messages

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