如何调整Pandas DataFrame行顺序,将Collect行设为首位?
解决方案:将Pandas DataFrame中'Collect'行设为首行
方法一:拆分拼接法
通过筛选目标行与剩余行,再拼接实现顺序调整:
# 筛选出Status为Collect的行 collect_row = df[df['Status'] == 'Collect'] # 筛选出其余行(排除Collect) remaining_rows = df[df['Status'] != 'Collect'] # 拼接为新DataFrame并重置索引 new_df = pd.concat([collect_row, remaining_rows]).reset_index(drop=True)
方法二:索引重排法
通过构造新的索引顺序直接调整行位置:
# 获取Collect行的索引位置 collect_idx = df[df['Status'] == 'Collect'].index[0] # 构建新的索引列表:先放Collect的索引,再放其余索引 new_order = [collect_idx] + [idx for idx in df.index if idx != collect_idx] # 按新索引排序并重置索引 new_df = df.loc[new_order].reset_index(drop=True)
两种方法均可实现将'Collect'行移至首行,其余行保留原有顺序的效果。执行后new_df的首行即为原DataFrame中Status为'Collect'的条目。
内容的提问来源于stack exchange,提问作者TimS
相关产品推荐
相关产品推荐

