>>> 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
Run Code Online (Sandbox Code Playgroud)
现在我想重新排列列序列,这使得'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
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个很长的'a','b','c','d'.....,我不想明确地列出列.我怎样才能做到这一点 ?
或者Pandas是否提供了这样的功能set_column_sequence(dataframe,col_name, seq)
,我可以这样做: set_column_sequence(df,'x',0)
和set_column_sequence(df,'y',1)
?
小智 30
你也可以这样做:
df = df[['x', 'y', 'a', 'b']]
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令获取列列表:
cols = list(df.columns.values)
Run Code Online (Sandbox Code Playgroud)
输出将产生如下所示:
['a', 'b', 'x', 'y']
Run Code Online (Sandbox Code Playgroud)
...然后在将其放入第一个函数之前,可以手动重新排列
And*_*den 10
可能有一个优雅的内置功能(但我还没有找到它).你可以写一个:
# 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]
Run Code Online (Sandbox Code Playgroud)
对于您的示例:set_column_sequence(df, ['x','y'])
将返回所需的输出.
如果你想要在DataFrame 末尾的seq而只是传入"front = False".
您可以执行以下操作:
df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})
df['x']=df.a + df.b
df['y']=df.a - df.b
Run Code Online (Sandbox Code Playgroud)
以这种方式创建任何您想要的列标题:
column_titles = ['x','y','a','b']
df.reindex(columns=column_titles)
Run Code Online (Sandbox Code Playgroud)
这将为您提供所需的输出
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63301 次 |
最近记录: |