将数据框列移动到最后一列

问题描述 投票:0回答:3

我想将数据框中的列移动到最后一列,我尝试过 使用

shift
。但这并不会改变立场。

import pandas a pd
df = #input dataframe
df['x'] = df['x'].shift(axis=1)
Error:
    raise ValueError(f"No axis named {axis} for object type {cls.__name__}")
ValueError: No axis named 1 for object type Series

还有其他选择吗?有人可以推荐一下吗?

python-3.x pandas dataframe shift
3个回答
4
投票

您可以

pop
并再次插入:

df['X'] = df.pop('X')

示例:

df = pd.DataFrame([list('axbc')], columns=['A', 'X', 'B', 'C'])
print(df)

   A  X  B  C
0  a  x  b  c


df['X'] = df.pop('X')
print(df)

   A  B  C  X
0  a  b  c  x

另一个更通用的选项是重新索引,为此您可以删除索引中最后移动的列并将它们添加到最后。优点是您可以一次处理多个列并选择更多列到不同的位置:

to_move = ['X']
new = df.columns.difference(to_move).to_list()+to_move
# ['A', 'B', 'C', 'X']

df = df[new]

1
投票

您可以将列拆分为“end_cols”和“other_cols”并将它们传递回选择器 -

# Borrowing @mozway's df
end_col = ['X'] 
other_cols = [col for col in df.columns if col not in end_col]
df[other_cols + end_col]

输出

   A  B  C  X
0  a  b  c  x

0
投票

您应该在弹出时插入列,而不是仅仅弹出列,否则您将丢失列

df.insert(len(df.columns)-1, 'X', df.pop('X'))
© www.soinside.com 2019 - 2024. All rights reserved.