如何重新排列 pandas 列的顺序? [英] How to rearrange Pandas column sequence?

查看:66
本文介绍了如何重新排列 pandas 列的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})
>>> df['x']=df.a + df.b
>>> df['y']=df.a - df.b
>>> df
   a  b   x  y
0  1  2   3 -1
1  2  4   6 -2
2  3  6   9 -3
3  4  8  12 -4

现在,我想重新排列列顺序,从而使"x","y"列成为第一个&第二列:

Now I want to rearrange the column sequence, which makes 'x','y' column to be the first & second columns by :

>>> df = df[['x','y','a','b']]
>>> df
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

但是如果我有一个很长的单词'a','b','c','d'.....,并且我不想明确列出这些列.我该怎么办?

But if I have a long coulmns 'a','b','c','d'....., and I don't want to explictly list the columns. How can I do that ?

或者Pandas是否提供类似set_column_sequence(dataframe,col_name, seq)的功能,以便我可以做到:set_column_sequence(df,'x',0)set_column_sequence(df,'y',1)?

Or Does Pandas provide a function like set_column_sequence(dataframe,col_name, seq) so that I can do : set_column_sequence(df,'x',0) and set_column_sequence(df,'y',1) ?

推荐答案

def _col_seq_set(df, col_list, seq_list):
    ''' set dataframe 'df' col_list's sequence by seq_list '''
    col_not_in_col_list = [x for x in list(df.columns) if x not in col_list]
    for i in range(len(col_list)):
        col_not_in_col_list.insert(seq_list[i], col_list[i])

    return df[col_not_in_col_list]
DataFrame.col_seq_set = _col_seq_set

这篇关于如何重新排列 pandas 列的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆