将列按名称移动到pandas中的表格前面

Boo*_*d16 61 python move shift dataframe pandas

这是我的df:

                             Net   Upper   Lower  Mid  Zsore
Answer option                                                
More than once a day          0%   0.22%  -0.12%   2    65 
Once a day                    0%   0.32%  -0.19%   3    45
Several times a week          2%   2.45%   1.10%   4    78
Once a week                   1%   1.63%  -0.40%   6    65
Run Code Online (Sandbox Code Playgroud)

如何按名称("Mid")将列移动到表的前面,索引0.这是它需要的样子:

                             Mid   Upper   Lower  Net  Zsore
Answer option                                                
More than once a day          2   0.22%  -0.12%   0%    65 
Once a day                    3   0.32%  -0.19%   0%    45
Several times a week          4   2.45%   1.10%   2%    78
Once a week                   6   1.63%  -0.40%   1%    65
Run Code Online (Sandbox Code Playgroud)

我当前的代码通过"df.columns.tolist()"按索引移动列,但Id喜欢按名称移动它.

EdC*_*ica 85

我们可以ix通过传递一个列表来重新排序:

In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
df
Out[28]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65
Run Code Online (Sandbox Code Playgroud)

另一种方法是对列进行引用并将其重新插入前面:

In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
df
Out[39]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65
Run Code Online (Sandbox Code Playgroud)

您还可以使用loc以获得与ix以后版本的pandas中不推荐使用相同的结果0.20.0:

df = df.loc[:, cols]
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在熊猫20.x中不建议使用.ix https://pandas.pydata.org/pandas-docs/stable/whatsnew.html#deprecate-ix (2认同)

nor*_*ius 50

我更喜欢这个解决方案:

col = df.pop("Mid")
df.insert(0, col.name, col)
Run Code Online (Sandbox Code Playgroud)

与其他建议的答案相比,它更易于阅读且速度更快。

def move_column_inplace(df, col, pos):
    col = df.pop(col)
    df.insert(pos, col.name, col)
Run Code Online (Sandbox Code Playgroud)

绩效评估:

对于此测试,当前最后一列在每次重复中移至最前面。就地方法通常性能更好。虽然 citynorman 的解决方案可以就地制作,但基于 Ed Chum 的方法.loc和基于sachinnm 的方法reindex不能。

虽然其他方法是通用的,但 citynorman 的解决方案仅限于pos=0. 我没有观察到df.loc[cols]和之间的任何性能差异df[cols],这就是为什么我没有包含其他一些建议。

我在 MacBook Pro(2015 年中)上使用 python 3.6.8 和 pandas 0.24.2 进行了测试。

import numpy as np
import pandas as pd

n_cols = 11
df = pd.DataFrame(np.random.randn(200000, n_cols),
                  columns=range(n_cols))

def move_column_inplace(df, col, pos):
    col = df.pop(col)
    df.insert(pos, col.name, col)

def move_to_front_normanius_inplace(df, col):
    move_column_inplace(df, col, 0)
    return df

def move_to_front_chum(df, col):
    cols = list(df)
    cols.insert(0, cols.pop(cols.index(col)))
    return df.loc[:, cols]

def move_to_front_chum_inplace(df, col):
    col = df[col]
    df.drop(col.name, axis=1, inplace=True)
    df.insert(0, col.name, col)
    return df

def move_to_front_elpastor(df, col):
    cols = [col] + [ c for c in df.columns if c!=col ]
    return df[cols] # or df.loc[cols]

def move_to_front_sachinmm(df, col):
    cols = df.columns.tolist()
    cols.insert(0, cols.pop(cols.index(col)))
    df = df.reindex(columns=cols, copy=False)
    return df

def move_to_front_citynorman_inplace(df, col):
    # This approach exploits that reset_index() moves the index
    # at the first position of the data frame.
    df.set_index(col, inplace=True)
    df.reset_index(inplace=True)
    return df

def test(method, df):
    col = np.random.randint(0, n_cols)
    method(df, col)

col = np.random.randint(0, n_cols)
ret_mine = move_to_front_normanius_inplace(df.copy(), col)
ret_chum1 = move_to_front_chum(df.copy(), col)
ret_chum2 = move_to_front_chum_inplace(df.copy(), col)
ret_elpas = move_to_front_elpastor(df.copy(), col)
ret_sach = move_to_front_sachinmm(df.copy(), col)
ret_city = move_to_front_citynorman_inplace(df.copy(), col)

# Assert equivalence of solutions.
assert(ret_mine.equals(ret_chum1))
assert(ret_mine.equals(ret_chum2))
assert(ret_mine.equals(ret_elpas))
assert(ret_mine.equals(ret_sach))
assert(ret_mine.equals(ret_city))
Run Code Online (Sandbox Code Playgroud)

结果

# For n_cols = 11:
%timeit test(move_to_front_normanius_inplace, df)
# 1.05 ms ± 42.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.68 ms ± 46.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_sachinmm, df)
# 3.24 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 3.84 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_elpastor, df)
# 3.85 ms ± 58.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 9.67 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


# For n_cols = 31:
%timeit test(move_to_front_normanius_inplace, df)
# 1.26 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.95 ms ± 260 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_sachinmm, df)
# 10.7 ms ± 348 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 11.5 ms ± 869 µs per loop (mean ± std. dev. of 7 runs, 100 loops each
%timeit test(move_to_front_elpastor, df)
# 11.4 ms ± 598 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 31.4 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@normanius。我明白了,在德克斯特的实验室里一直在努力工作。:-) 很好的解决方案。奥卡姆剃刀。简单又优雅。 (4认同)
  • 很好的解决方案。但是,我们不应该将带有插入列的修改后的 df 显式分配给原始 df。因此,我们需要执行“df.insert(0, col.name, col)”,而不是“df = df.insert(0, col.name, col)”。不过,您在函数“move_column_inplace()”中正确地拥有了它​​。 (2认同)

Sac*_*nmm 35

您可以在pandas中使用df.reindex()函数.df是

                      Net  Upper   Lower  Mid  Zsore
Answer option                                      
More than once a day  0%  0.22%  -0.12%    2     65
Once a day            0%  0.32%  -0.19%    3     45
Several times a week  2%  2.45%   1.10%    4     78
Once a week           1%  1.63%  -0.40%    6     65
Run Code Online (Sandbox Code Playgroud)

定义列名列表

cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']
Run Code Online (Sandbox Code Playgroud)

将列名移动到您想要的位置

cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
Run Code Online (Sandbox Code Playgroud)

然后使用df.reindex()函数重新排序

df = df.reindex(columns= cols)
Run Code Online (Sandbox Code Playgroud)

out put是:df

                      Mid  Upper   Lower Net  Zsore
Answer option                                      
More than once a day    2  0.22%  -0.12%  0%     65
Once a day              3  0.32%  -0.19%  0%     45
Several times a week    4  2.45%   1.10%  2%     78
Once a week             6  1.63%  -0.40%  1%     65
Run Code Online (Sandbox Code Playgroud)

  • 这将使内在的熊猫变得非常整洁-将列“ Y”移到n位... (5认同)

cit*_*man 15

我不喜欢我必须在其他解决方案中明确指定所有其他列,所以这对我来说效果最好.虽然对于大型数据帧来说可能会很慢......?

df = df.set_index('Mid').reset_index()


elP*_*tor 14

也许我错过了一些东西,但是许多答案似乎过于复杂。您应该只需要在一个列表中设置列即可:

列在最前面:

df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]
Run Code Online (Sandbox Code Playgroud)

或者,如果您想将其移到后面:

df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]
Run Code Online (Sandbox Code Playgroud)

或者,如果您想移动不止一列:

cols_to_move = ['Mid', 'Zsore']
df           = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]
Run Code Online (Sandbox Code Playgroud)


Bha*_*era 7

这是一组通用代码,我经常使用它们来重新排列列的位置。您可能会发现它很有用。

cols = df.columns.tolist()
n = int(cols.index('Mid'))
cols = [cols[n]] + cols[:n] + cols[n+1:]
df = df[cols]
Run Code Online (Sandbox Code Playgroud)

  • 理想情况下,解释您的答案以及使其成为一个好的解决方案的原因,而不仅要发布一段代码。您有投票的风险 (3认同)

Dus*_*ell 5

要重新排序 DataFrame 的行,只需使用如下列表即可。

df = df[['Mid', 'Net', 'Upper', 'Lower', 'Zsore']]
Run Code Online (Sandbox Code Playgroud)

这使得稍后阅读代码时所做的事情非常明显。还可以使用:

df.columns
Out[1]: Index(['Net', 'Upper', 'Lower', 'Mid', 'Zsore'], dtype='object')
Run Code Online (Sandbox Code Playgroud)

然后剪切和粘贴以重新排序。


对于具有许多列的 DataFrame,将列列表存储在一个变量中,并将所需的列弹出到列表的前面。下面是一个例子:

cols = [str(col_name) for col_name in range(1001)]
data = np.random.rand(10,1001)
df = pd.DataFrame(data=data, columns=cols)

mv_col = cols.pop(cols.index('77'))
df = df[[mv_col] + cols]
Run Code Online (Sandbox Code Playgroud)

现在df.columns有。

Index(['77', '0', '1', '2', '3', '4', '5', '6', '7', '8',
       ...
       '991', '992', '993', '994', '995', '996', '997', '998', '999', '1000'],
      dtype='object', length=1001)
Run Code Online (Sandbox Code Playgroud)