我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
只需键入要更改的列名,然后为新位置设置索引。
def change_column_order(df, col_name, index):
cols = df.columns.tolist()
cols.remove(col_name)
cols.insert(index, col_name)
return df[cols]
对于您的情况,这将是:
df = change_column_order(df, 'mean', 0)
其他回答
DataFrame.sort_index(axis=1)非常干净。请在此处检查文档。然后凹入
这个问题以前已经回答过,但reindex_axis现在已被弃用,因此我建议使用:
df = df.reindex(sorted(df.columns), axis=1)
对于那些想要指定他们想要的顺序而不是仅仅对它们进行排序的人来说,下面列出了解决方案:
df = df.reindex(['the','order','you','want'], axis=1)
现在,如何对列名列表排序真的不是熊猫问题,而是Python列表操作问题。有很多方法可以做到这一点,我认为这个答案有一个非常简洁的方法。
大多数答案都不够概括,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]
您可以使用以下名称列表对数据帧列进行重新排序:
df=df.filter(list_of_col_name)
在您的情况下,
df = df.reindex(columns=['mean',0,1,2,3,4])
会做你想做的事。
在我的情况下(一般形式):
df = df.reindex(columns=sorted(df.columns))
df = df.reindex(columns=(['opened'] + list([a for a in df.columns if a != 'opened']) ))