首页 > 解决方案 > 将特定行移动到熊猫数据框顶部或底部的功能

问题描述

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

这些是将行移动到顶部/底部的 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

我的问题是:

标签: pythonpandasdataframeindexingrow

解决方案


你的问题是这两行:

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

idx是一个列表并idx.pop(index_to_shift)删除索引index_to_shift为的项目idx,这不一定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

推荐阅读