按名称将行移动到df中所需的位置

2024-05-29 04:13:44 发布

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

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

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

我想选择一个给定的行,比如按名称,比如说“apple”,然后将它移动到一个新位置,比如-1(最后一行的第二行)

期望输出

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

有什么功能可以实现这一点吗


Tags: 功能名称appledfgoogleothermercswatch
3条回答

我不知道有任何内置函数,但一种方法是只操作索引,然后使用新索引对数据帧重新排序(假设所有索引值都是唯一的):

name = 'apple'
position = -1

new_index = [i for i in df.index if i != name]
new_index.insert(position, name)
df = df.loc[new_index]

结果:

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

这似乎很好,我正在使用^{}^{}

df.reindex(df.index.insert(-1,'apple').drop_duplicates(keep='last'))

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

使用^{}删除值,使用^{}向新索引添加值,最后使用^{}^{}更改行的顺序:

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

相关问题 更多 >

    热门问题