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

标签 python pandas dataframe indexing

我有一个 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

关于python - 按名称将行移动到 df 中的所需位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56951576/

相关文章:

python - Mongo链接/引用: most efficient way?示例?

python - 通过多个变量的模糊匹配来匹配实体

python - 查找 Dataframe : Python pandas module 中的最后一行

pandas - 将 pandas 数据框与间隔数据(从上到下)结合起来,并以尽可能最小的间隔创建新的 df

python - 将函数应用于多个数据框列

python - 在 numpy 3D 数组中查找值索引

python - 在 numpy 中计算对角线和

python - Pandas 中的 Vlookup 功能完全相同

python - 根据条件删除 pandas DataFrame 中的重复行

python - 将当前行和上一行的差异附加到新列,用于多列