我有一个 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.reindex
或 DataFrame.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