Python Forum
How to shift data frame rows of specified column
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to shift data frame rows of specified column
#1
Hi,
I have dataframe, I wan to define new column same as Column1, and re-arrange the new columns rows as:
new_col rows 0-end should be replaced with first column row1-end

import pandas as pd
df = pd.DataFrame({'Col1': [1, 2, 3, 4, 5],'Col2': [6, 7, 8, 9, 10],
                   'Col3': [11, 12, 13, 14, 15]})

df['new_col'] = df['Col1']
df[0:-1,'new_col']=df.ix[1:,'Col1']
TypeError: unhashable type: 'slice'

my desired output:
Col1  Col2 Col3 new_col
1     6    11   2
2     7    12   3 
3     8    13   4
4     9    14   5
5     10   15   5

I use this way, and it works:
df['new_col']=df['new_col'].shift(-1)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Grouping in pandas/multi-index data frame Aleqsie 3 607 Jan-06-2024, 03:55 PM
Last Post: deanhystad
  Filtering Data Frame, with another value NewBiee 9 1,331 Aug-21-2023, 10:53 AM
Last Post: NewBiee
  Make unique id in vectorized way based on text data column with similarity scoring ill8 0 861 Dec-12-2022, 03:22 AM
Last Post: ill8
  Exporting data frame to excel dyerlee91 0 1,604 Oct-05-2021, 11:34 AM
Last Post: dyerlee91
  What if a column has about 90% of data as outliers? Asahavey17 1 1,784 Aug-23-2021, 04:55 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 2,655 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Adding a new column to a Panda Data Frame rsherry8 2 2,083 Jun-06-2021, 06:49 PM
Last Post: jefsummers
  grouped data frame glitter 0 1,577 Feb-02-2021, 11:22 AM
Last Post: glitter
  Redistributing column data metro17 2 1,651 Nov-28-2020, 05:53 PM
Last Post: metro17
  Combine groupby() and shift() in pandas rama27 0 4,153 Nov-17-2020, 09:49 PM
Last Post: rama27

Forum Jump:

User Panel Messages

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