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
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 690 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 654 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  pandas : problem with conditional filling of a column Xigris 2 594 Jul-22-2023, 11:44 AM
Last Post: Xigris
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 799 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Basic Pandas, obtaining a value from column and row JamesOzone 2 1,056 Jun-30-2022, 07:16 PM
Last Post: jefsummers
  Float Slider - Affecting Values in Column 'Pandas' planckepoch86 0 1,370 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 1,602 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 3,229 Oct-23-2021, 04:35 AM
Last Post: JaneTan
  How to combine multiple rows of strings into one using pandas? shantanu97 1 3,098 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,531 Jul-17-2021, 09:09 AM
Last Post: JaneTan

Forum Jump:

User Panel Messages

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