>>> 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
但是如果我有一个很长的coulmns 'a','b','c','d'.....,我不想显式地列出这些列。我该怎么做呢?
或者,Pandas提供了一个像set_column_sequence(dataframe,col_name, seq)
这样的函数,这样我就可以做:set_column_sequence(df,'x',0)
和set_column_sequence(df,'y',1)
?
发布于 2013-03-27 11:49:35
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
发布于 2014-05-19 15:32:07
你也可以这样做:
df = df[['x', 'y', 'a', 'b']]
您可以使用以下命令获取列的列表:
cols = list(df.columns.values)
输出将产生类似如下的结果:
['a', 'b', 'x', 'y']
然后,在将...which放入第一个函数之前,可以很容易地手动重新排列它
发布于 2012-09-08 10:41:23
可能有一个优雅的内置函数(但我还没有找到它)。你可以写一个:
# 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“。
https://stackoverflow.com/questions/12329853
复制相似问题