Swapping rows within the same pandas dataframe

后端 未结 3 490
清歌不尽
清歌不尽 2021-01-17 20:55

I\'m trying to swap the rows within the same DataFrame in pandas.

I\'ve tried running

a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns          


        
相关标签:
3条回答
  • 2021-01-17 21:35

    Use a temporary varaible to store the value using .copy(), because you are changing the values while assigning them on chain i.e. Unless you use copy the data will be changed directly.

    a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
    b, c = a.iloc[0], a.iloc[1]
    
    
    temp = a.iloc[0].copy()
    a.iloc[0] = c
    a.iloc[1] = temp
    

    Or you can directly use copy like

    a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
    b, c = a.iloc[0].copy(), a.iloc[1].copy()
    a.iloc[0],a.iloc[1] = c,b
    
    0 讨论(0)
  • 2021-01-17 21:43

    In this way, it can be extrapolated to more complex situations:

        a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
        rows = a.index.tolist()
        rows = rows[-1:]+rows[:-1]
        a=a.loc[rows]
    
    0 讨论(0)
  • 2021-01-17 21:50

    The accepted answer does not make changes the index name.

    If you only want to alter the order of rows you should use dataframe.reindex(arraylike). Notice that the index has changed.

    0 讨论(0)
提交回复
热议问题