python - 将特定行移动到熊猫数据框顶部或底部的功能
问题描述
我有两个函数分别将一行熊猫数据框移动到顶部或底部。在将它们多次应用于数据框后,它们似乎无法正常工作。
这些是将行移动到顶部/底部的 2 个功能:
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
注意:我不想reset_index
为返回的 df.
例子:
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 = df.index.tolist()
idx.pop(index_to_shift)
idx
是一个列表并idx.pop(index_to_shift)
删除索引index_to_shift
为的项目idx
,这不一定index_to_shift
像第二种情况那样被重视。
试试这个功能:
def shift_row_to_bottom(df, index_to_shift):
idx = [i for i in df.index if i!=index_to_shift]
return df.loc[idx+[index_to_shift]]
# call the function twice
for i in range(2): df = shift_row_to_bottom(df, 2)
输出:
Country ID City short_name
0 USA 11 New-York NY
1 GE 22 Berlin Ber
3 BR 44 London Lon
4 France 55 Paris Pa
2 Russia 33 Moscow Mosc
推荐阅读
- azure - 针对 ProtectedWebWebi 的 Azure AD 身份验证
- python - 通过从 python 文件中引用来安装 requirements.txt 中存在的包
- python - 如何使用自定义相等函数从 Python 中的自定义对象列表中删除重复项?
- flutter - Flutter/解析部分url
- etag - minio etag是如何生成的
- pandas - 如何用 max() 值填充熊猫数据框
- bash - 如何识别如何运行脚本?
- c# - c#中的iform文件序列化和反序列化
- typo3 - 如何在 TYPO3 中使用 Mask CE 的 Appearnce 选项卡?
- node.js - Textract 异步读取 PDF