28
>>> 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' 列成为第一列和第二列:

>>> 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'......,并且我不想明确列出这些列。我怎样才能做到这一点 ?

或者 Pandas 是否提供了set_column_sequence(dataframe,col_name, seq)这样的功能,我可以这样做: set_column_sequence(df,'x',0)set_column_sequence(df,'y',1)

4

6 回答 6

47

你也可以这样做:

df = df[['x', 'y', 'a', 'b']]

您可以通过以下方式获取列列表:

cols = list(df.columns.values)

输出将产生如下内容:

['a', 'b', 'x', 'y']

...然后很容易在将其放入第一个函数之前手动重新排列

于 2014-05-19T15:32:06.533 回答
11

可能有一个优雅的内置函数(但我还没有找到)。你可以写一个:

# reorder columns
def set_column_sequence(dataframe, seq, front=True):
    '''Takes a dataframe and a subsequence of its columns,
       returns dataframe with seq as first columns if "front" is True,
       and seq as last columns if "front" is False.
    '''
    cols = seq[:] # copy so we don't mutate seq
    for x in dataframe.columns:
        if x not in cols:
            if front: #we want "seq" to be in the front
                #so append current column to the end of the list
                cols.append(x)
            else:
                #we want "seq" to be last, so insert this
                #column in the front of the new column list
                #"cols" we are building:
                cols.insert(0, x)
return dataframe[cols]

对于您的示例:set_column_sequence(df, ['x','y'])将返回所需的输出。

如果您想要在DataFrame末尾的 seq,只需传入“front=False”即可。

于 2012-09-08T10:41:23.073 回答
6

您可以执行以下操作:

df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})

df['x']=df.a + df.b
df['y']=df.a - df.b

以这种方式创建您想要的任何顺序的列标题:

column_titles = ['x','y','a','b']

df.reindex(columns=column_titles)

这将为您提供所需的输出

于 2017-11-20T14:53:03.193 回答
3
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
于 2013-03-27T11:49:35.467 回答
1

I would suggest you just write a function to do what you're saying probably using drop (to delete columns) and insert to insert columns at a position. There isn't an existing API function to do what you're describing.

于 2012-09-08T20:41:11.897 回答
0

随意忽略此解决方案,因为从索引中减去列表不会保留原始索引的顺序,如果这很重要的话。

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8
于 2012-09-08T23:58:58.870 回答