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
  pandas : problem with conditional filling of a column Xigris 2 312 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 619 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Basic Pandas, obtaining a value from column and row JamesOzone 2 807 Jun-30-2022, 07:16 PM
Last Post: jefsummers
  Float Slider - Affecting Values in Column 'Pandas' planckepoch86 0 1,097 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,355 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 2,683 Oct-23-2021, 04:35 AM
Last Post: JaneTan
  How to combine multiple rows of strings into one using pandas? shantanu97 1 2,708 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,375 Jul-17-2021, 09:09 AM
Last Post: JaneTan
  Python Pandas: How do I sumproduct by rows with an if condition? JaneTan 2 4,459 Jul-13-2021, 11:36 AM
Last Post: jefsummers
  Partial Matching Rows In Pandas DataFrame Query eddywinch82 1 2,013 Jul-08-2021, 06:32 PM
Last Post: eddywinch82

Forum Jump:

User Panel Messages

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