我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
我自己也遇到了一个类似的问题,只是想补充一下我已经解决的问题。我喜欢用于更改列顺序的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稍快,但我认为我更喜欢后者,因为它的直接性。
其他回答
这里有一个非常简单的答案(只有一行)。
在将“n”列添加到df中之后,可以执行以下操作。
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
df['mean'] = df.mean(1)
df
0 1 2 3 4 mean
0 0.929616 0.316376 0.183919 0.204560 0.567725 0.440439
1 0.595545 0.964515 0.653177 0.748907 0.653570 0.723143
2 0.747715 0.961307 0.008388 0.106444 0.298704 0.424512
3 0.656411 0.809813 0.872176 0.964648 0.723685 0.805347
4 0.642475 0.717454 0.467599 0.325585 0.439645 0.518551
5 0.729689 0.994015 0.676874 0.790823 0.170914 0.672463
6 0.026849 0.800370 0.903723 0.024676 0.491747 0.449473
7 0.526255 0.596366 0.051958 0.895090 0.728266 0.559587
8 0.818350 0.500223 0.810189 0.095969 0.218950 0.488736
9 0.258719 0.468106 0.459373 0.709510 0.178053 0.414752
### here you can add below line and it should work
# Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.
df = df[list(('mean',0, 1, 2,3,4))]
df
mean 0 1 2 3 4
0 0.440439 0.929616 0.316376 0.183919 0.204560 0.567725
1 0.723143 0.595545 0.964515 0.653177 0.748907 0.653570
2 0.424512 0.747715 0.961307 0.008388 0.106444 0.298704
3 0.805347 0.656411 0.809813 0.872176 0.964648 0.723685
4 0.518551 0.642475 0.717454 0.467599 0.325585 0.439645
5 0.672463 0.729689 0.994015 0.676874 0.790823 0.170914
6 0.449473 0.026849 0.800370 0.903723 0.024676 0.491747
7 0.559587 0.526255 0.596366 0.051958 0.895090 0.728266
8 0.488736 0.818350 0.500223 0.810189 0.095969 0.218950
9 0.414752 0.258719 0.468106 0.459373 0.709510 0.178053
大多数答案都不够概括,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]
我有一个在panda中重新排序列名的非常具体的用例。有时我在基于现有列的数据帧中创建一个新列。默认情况下,panda将在末尾插入我的新列,但我希望新列插入到它派生的现有列旁边。
def rearrange_list(input_list, input_item_to_move, input_item_insert_here):
'''
Helper function to re-arrange the order of items in a list.
Useful for moving column in pandas dataframe.
Inputs:
input_list - list
input_item_to_move - item in list to move
input_item_insert_here - item in list, insert before
returns:
output_list
'''
# make copy for output, make sure it's a list
output_list = list(input_list)
# index of item to move
idx_move = output_list.index(input_item_to_move)
# pop off the item to move
itm_move = output_list.pop(idx_move)
# index of item to insert here
idx_insert = output_list.index(input_item_insert_here)
# insert item to move into here
output_list.insert(idx_insert, itm_move)
return output_list
import pandas as pd
# step 1: create sample dataframe
df = pd.DataFrame({
'motorcycle': ['motorcycle1', 'motorcycle2', 'motorcycle3'],
'initial_odometer': [101, 500, 322],
'final_odometer': [201, 515, 463],
'other_col_1': ['blah', 'blah', 'blah'],
'other_col_2': ['blah', 'blah', 'blah']
})
print('Step 1: create sample dataframe')
display(df)
print()
# step 2: add new column that is difference between final and initial
df['change_odometer'] = df['final_odometer']-df['initial_odometer']
print('Step 2: add new column')
display(df)
print()
# step 3: rearrange columns
ls_cols = df.columns
ls_cols = rearrange_list(ls_cols, 'change_odometer', 'final_odometer')
df=df[ls_cols]
print('Step 3: rearrange columns')
display(df)
这个问题以前已经回答过,但reindex_axis现在已被弃用,因此我建议使用:
df = df.reindex(sorted(df.columns), axis=1)
对于那些想要指定他们想要的顺序而不是仅仅对它们进行排序的人来说,下面列出了解决方案:
df = df.reindex(['the','order','you','want'], axis=1)
现在,如何对列名列表排序真的不是熊猫问题,而是Python列表操作问题。有很多方法可以做到这一点,我认为这个答案有一个非常简洁的方法。
另一种选择是使用set_index()方法,后跟reset_index()。请注意,我们首先pop()将要移动到数据帧前面的列,以便在重置索引时避免名称冲突:
df.set_index(df.pop('column_name'), inplace=True)
df.reset_index(inplace=True)
有关详细信息,请参阅How to change the order of dataframe columns in panda。