我有一个 df 看起来像这样:

         a   b 
apple  | 7 | 2 | 
google | 8 | 8 | 
swatch | 6 | 6 | 
merc   | 7 | 8 | 
other  | 8 | 9 | 

我想按名称选择给定的行,说“苹果”并将其移动到新位置,比如 -1(倒数第二行)

期望的输出

         a   b 
google | 8 | 8 | 
swatch | 6 | 6 | 
merc   | 7 | 8 | 
apple  | 7 | 2 | 
other  | 8 | 9 | 

有没有什么函数可以实现这个?

请您参考如下方法:

使用Index.difference用于删除值和 numpy.insert为新索引增加值(value),最后使用 DataFrame.reindexDataFrame.loc更改行的顺序:

a = 'apple' 
 
idx = np.insert(df.index.difference([a], sort=False), -1, a) 
print (idx) 
Index(['google', 'swatch', 'merc', 'apple', 'other'], dtype='object') 
 
df = df.reindex(idx) 
#alternative 
#df = df.loc[idx] 
print (df) 
        a  b 
google  8  8 
swatch  6  6 
merc    7  8 
apple   7  2 
other   8  9 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!