我有两个函数,分别将数据帧的一行移到顶部或底部。在将它们多次应用于数据帧之后,它们似乎无法正常工作
以下是将行移动到顶部/底部的两个功能:
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
我的问题是:
您的问题在于以下两行:
idx
是一个列表,idx.pop(index_to_shift)
删除idx
的index_to_shift
索引处的项,该项的值不一定像第二种情况那样index_to_shift
尝试此功能:
输出:
相关问题 更多 >
编程相关推荐