Python Forum
How to diff pandas rows and modify column value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to diff pandas rows and modify column value
#1
Hi,
I have bewlow pandas dataframe:

ID  sub_set  group Rank
A1   A.0     A     1
A2   A.0     A     2
A1   A.1     A     3
A3   A.0     A     4  
A4   A.0     A     5
A5   A.0     A     6
I want to reinitiate the Rank at each instance where currenr row value in "sub_set" columns is different from previous row value.
Also get row indices.

desired output:

ID  sub_set  group Rank
A1   A.0     A     1
A2   A.0     A     2
A1   A.1     A     1
A3   A.0     A     1  
A4   A.0     A     2
A5   A.0     A     3
I try using:

idx= df['sub_set'].diff(periods=-1)

but it give error:
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Pleae some one help, how to achieve this.

idx = df['sub_set'].diff(periods=1)

I used below:
df['value'] = (df[['sub_set']] != df[['sub_set']].shift()).any(axis=1).cumsum()
but I dont want to sum. I want to reset row value to 1, and increase continuously until next instance(next two rows are different) occures.
Reply
#2
I used below:
df['value'] = (df[['sub_set']] != df[['sub_set']].shift()).any(axis=1).cumsum()
but I dont want to sum. I want to reset row value to 1, and increase continuously until next instance(next two rows are different) occures.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 145 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Basic Pandas, obtaining a value from column and row JamesOzone 2 347 Jun-30-2022, 07:16 PM
Last Post: jefsummers
  Float Slider - Affecting Values in Column 'Pandas' planckepoch86 0 607 Jan-22-2022, 02:18 PM
Last Post: planckepoch86
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 891 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  pandas pivot table: How to find count for each group in Index and Column JaneTan 0 1,550 Oct-23-2021, 04:35 AM
Last Post: JaneTan
  How to combine multiple rows of strings into one using pandas? shantanu97 1 2,057 Aug-22-2021, 05:26 AM
Last Post: klllmmm
  Python Pandas: How do I extract all the >1000 data from a certain column? JaneTan 0 1,021 Jul-17-2021, 09:09 AM
Last Post: JaneTan
  Python Pandas: How do I sumproduct by rows with an if condition? JaneTan 2 2,643 Jul-13-2021, 11:36 AM
Last Post: jefsummers
  Partial Matching Rows In Pandas DataFrame Query eddywinch82 1 1,414 Jul-08-2021, 06:32 PM
Last Post: eddywinch82
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 1,402 May-04-2021, 10:51 PM
Last Post: rhat398

Forum Jump:

User Panel Messages

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