将特定行移动到 pandas 数据框的顶部或底部的函数

Function to move specific row to top or bottom of pandas dataframe

我有两个函数,分别将 pandas 数据框的一行移动到顶部或底部。将它们多次应用于数据框后,它们似乎无法正常工作。

这些是将行移动到顶部/底部的 2 个函数:

def shift_row_to_bottom(df, index_to_shift):
  """Shift row, given by index_to_shift, to bottom of df."""
  
  idx = df.index.tolist()
  idx.pop(index_to_shift)
  df = df.reindex(idx + [index_to_shift])
  
  return df


def shift_row_to_top(df, index_to_shift):
  """Shift row, given by index_to_shift, to top of df."""
  
  idx = df.index.tolist()
  idx.pop(index_to_shift)
  df = df.reindex([index_to_shift] + idx)
  
  return df

注意:我不想reset_index返回的df。

示例:

df = pd.DataFrame({'Country' : ['USA', 'GE', 'Russia', 'BR', 'France'], 
                   'ID' : ['11', '22', '33','44', '55'],
                   'City' : ['New-York', 'Berlin', 'Moscow', 'London', 'Paris'],
                   'short_name' : ['NY', 'Ber', 'Mosc','Lon', 'Pa']
                  })
df =

    Country  ID  City    short_name
0   USA      11  New-York   NY
1   GE       22  Berlin     Ber
2   Russia   33  Moscow     Mosc
3   BR       44  London     Lon
4   France   55  Paris      Pa

这是我的数据框:

现在,第一次应用函数。将索引为 0 的行移至底部:

df_shifted = shift_row_to_bottom(df,0)

df_shifted = 
Country     ID  City      short_name
1   GE      22  Berlin    Ber
2   Russia  33  Moscow    Mosc
3   BR      44  London    Lon
4   France  55  Paris     Pa
0   USA     11  New-York  NY

结果正是我想要的

现在,再次应用函数。这次将索引为 2 的行移到底部:

df_shifted = shift_row_to_bottom(df_shifted,2)

df_shifted =
Country     ID  City    short_name
1   GE      22  Berlin    Ber
2   Russia  33  Moscow    Mosc
4   France  55  Paris     Pa
0   USA     11  New-York  NY
2   Russia  33  Moscow    Mosc

好吧,这不是我所期待的。当我想第二次应用该功能时,肯定有问题。问题类似于函数 shift_row_to_top.

我的问题是:

你的问题是这两行:

  idx = df.index.tolist()
  idx.pop(index_to_shift)

idx 是一个列表,idx.pop(index_to_shift) 删除了 idx 的索引 index_to_shift 处的项目,它不一定像第二个那样被赋值为 index_to_shift案例.

试试这个功能:

def shift_row_to_bottom(df, index_to_shift):
    idx = [i for i in df.index if i!=index_to_shift]
    return df.loc[idx+[index_to_shift]]

# call the function twice
for i in range(2): df = shift_row_to_bottom(df, 2)

输出:

  Country  ID      City short_name
0     USA  11  New-York         NY
1      GE  22    Berlin        Ber
3      BR  44    London        Lon
4  France  55     Paris         Pa
2  Russia  33    Moscow       Mosc