我有以下DataFrame(df):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
我通过分配添加更多列:
df['mean'] = df.mean(1)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
我有以下DataFrame(df):
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
我通过分配添加更多列:
df['mean'] = df.mean(1)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
假设您有列为A、B、C的df。
最简单的方法是:
df = df.reindex(['B','C','A'], axis=1)
其他回答
我自己也遇到了一个类似的问题,只是想补充一下我已经解决的问题。我喜欢用于更改列顺序的reindex_axis()方法。这是有效的:
df = df.reindex_axis(['mean'] + list(df.columns[:-1]), axis=1)
另一种基于@Jorge评论的方法:
df = df.reindex(columns=['mean'] + list(df.columns[:-1]))
虽然reindex_axis在微基准测试中似乎比reindex稍快,但我认为我更喜欢后者,因为它的直接性。
这里有一种移动一个现有列的方法,它将修改现有的数据帧。
my_column = df.pop('column name')
df.insert(3, my_column.name, my_column) # Is in-place
DataFrame.sort_index(axis=1)非常干净。请在此处检查文档。然后凹入
大多数答案都不够概括,panda reindex_axis方法有点乏味,因此我提供了一个简单的函数,可以使用字典将任意数量的列移动到任意位置,其中key=列名,value=要移动到的位置。如果数据帧很大,请将True传递给“big_data”,那么函数将返回有序的列列表。您可以使用此列表来分割数据。
def order_column(df, columns, big_data = False):
"""Re-Orders dataFrame column(s)
Parameters :
df -- dataframe
columns -- a dictionary:
key = current column position/index or column name
value = position to move it to
big_data -- boolean
True = returns only the ordered columns as a list
the user user can then slice the data using this
ordered column
False = default - return a copy of the dataframe
"""
ordered_col = df.columns.tolist()
for key, value in columns.items():
ordered_col.remove(key)
ordered_col.insert(value, key)
if big_data:
return ordered_col
return df[ordered_col]
# e.g.
df = pd.DataFrame({'chicken wings': np.random.rand(10, 1).flatten(), 'taco': np.random.rand(10,1).flatten(),
'coffee': np.random.rand(10, 1).flatten()})
df['mean'] = df.mean(1)
df = order_column(df, {'mean': 0, 'coffee':1 })
>>>
col = order_column(df, {'mean': 0, 'coffee':1 }, True)
col
>>>
['mean', 'coffee', 'chicken wings', 'taco']
# you could grab it by doing this
df = df[col]
一种简单的方法是使用set(),特别是当您有一长串列并且不想手动处理它们时:
cols = list(set(df.columns.tolist()) - set(['mean']))
cols.insert(0, 'mean')
df = df[cols]