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

2024-10-04 07:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

以下是将行移动到顶部/底部的两个功能:

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

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

示例:

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

我的问题是:

  • 这是怎么回事
  • 是否有更好的方法将特定行移到数据帧的顶部/底部?也许是熊猫的功能
  • 如果没有,你会怎么做

Tags: to数据函数dfindexshiftcountryrow
1条回答
网友
1楼 · 发布于 2024-10-04 07:32:38

您的问题在于以下两行:

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

idx是一个列表,idx.pop(index_to_shift)删除idxindex_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

相关问题 更多 >