我有以下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)
如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?
当前回答
下面是一个超级简单的方法示例。如果您要从excel复制标题,请使用.split('\t')
df = df['FILE_NAME DISPLAY_PATH SHAREPOINT_PATH RETAILER LAST_UPDATE'.split()]
其他回答
我想在一个数据帧前面加上两列,我不知道所有列的确切名称,因为它们是从之前的pivot语句生成的。所以,如果你也遇到同样的情况:把你知道名字的列放在前面,然后让它们跟着“所有其他列”,我提出了以下一般解决方案:
df = df.reindex_axis(['Col1','Col2'] + list(df.columns.drop(['Col1','Col2'])), axis=1)
我相信,如果你知道另一列的位置,@Aman的答案是最好的。
如果您不知道mean的位置,但只有它的名称,则不能直接使用cols=cols[-1:]+cols[:-1]。以下是我接下来能想到的最好的东西:
meanDf = pd.DataFrame(df.pop('mean'))
# now df doesn't contain "mean" anymore. Order of join will move it to left or right:
meanDf.join(df) # has mean as first column
df.join(meanDf) # has mean as last column
一种简单的方法是用列列表重新分配数据帧,根据需要重新排列。
这就是你现在拥有的:
In [6]: df
Out[6]:
0 1 2 3 4 mean
0 0.445598 0.173835 0.343415 0.682252 0.582616 0.445543
1 0.881592 0.696942 0.702232 0.696724 0.373551 0.670208
2 0.662527 0.955193 0.131016 0.609548 0.804694 0.632596
3 0.260919 0.783467 0.593433 0.033426 0.512019 0.436653
4 0.131842 0.799367 0.182828 0.683330 0.019485 0.363371
5 0.498784 0.873495 0.383811 0.699289 0.480447 0.587165
6 0.388771 0.395757 0.745237 0.628406 0.784473 0.588529
7 0.147986 0.459451 0.310961 0.706435 0.100914 0.345149
8 0.394947 0.863494 0.585030 0.565944 0.356561 0.553195
9 0.689260 0.865243 0.136481 0.386582 0.730399 0.561593
In [7]: cols = df.columns.tolist()
In [8]: cols
Out[8]: [0L, 1L, 2L, 3L, 4L, 'mean']
按任意方式重新排列列。这是我将最后一个元素移动到第一个位置的方式:
In [12]: cols = cols[-1:] + cols[:-1]
In [13]: cols
Out[13]: ['mean', 0L, 1L, 2L, 3L, 4L]
然后重新排序数据帧,如下所示:
In [16]: df = df[cols] # OR df = df.ix[:, cols]
In [17]: df
Out[17]:
mean 0 1 2 3 4
0 0.445543 0.445598 0.173835 0.343415 0.682252 0.582616
1 0.670208 0.881592 0.696942 0.702232 0.696724 0.373551
2 0.632596 0.662527 0.955193 0.131016 0.609548 0.804694
3 0.436653 0.260919 0.783467 0.593433 0.033426 0.512019
4 0.363371 0.131842 0.799367 0.182828 0.683330 0.019485
5 0.587165 0.498784 0.873495 0.383811 0.699289 0.480447
6 0.588529 0.388771 0.395757 0.745237 0.628406 0.784473
7 0.345149 0.147986 0.459451 0.310961 0.706435 0.100914
8 0.553195 0.394947 0.863494 0.585030 0.565944 0.356561
9 0.561593 0.689260 0.865243 0.136481 0.386582 0.730399
要根据其他列的名称将现有列设置为右侧/左侧,请执行以下操作:
def df_move_column(df, col_to_move, col_left_of_destiny="", right_of_col_bool=True):
cols = list(df.columns.values)
index_max = len(cols) - 1
if not right_of_col_bool:
# set left of a column "c", is like putting right of column previous to "c"
# ... except if left of 1st column, then recursive call to set rest right to it
aux = cols.index(col_left_of_destiny)
if not aux:
for g in [x for x in cols[::-1] if x != col_to_move]:
df = df_move_column(
df,
col_to_move=g,
col_left_of_destiny=col_to_move
)
return df
col_left_of_destiny = cols[aux - 1]
index_old = cols.index(col_to_move)
index_new = 0
if len(col_left_of_destiny):
index_new = cols.index(col_left_of_destiny) + 1
if index_old == index_new:
return df
if index_new < index_old:
index_new = np.min([index_new, index_max])
cols = (
cols[:index_new]
+ [cols[index_old]]
+ cols[index_new:index_old]
+ cols[index_old + 1 :]
)
else:
cols = (
cols[:index_old]
+ cols[index_old + 1 : index_new]
+ [cols[index_old]]
+ cols[index_new:]
)
df = df[cols]
return df
E.g.
cols = list("ABCD")
df2 = pd.DataFrame(np.arange(4)[np.newaxis, :], columns=cols)
for k in cols:
print(30 * "-")
for g in [x for x in cols if x != k]:
df_new = df_move_column(df2, k, g)
print(f"{k} after {g}: {df_new.columns.values}")
for k in cols:
print(30 * "-")
for g in [x for x in cols if x != k]:
df_new = df_move_column(df2, k, g, right_of_col_bool=False)
print(f"{k} before {g}: {df_new.columns.values}")
输出:
大多数答案都不够概括,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]