given df
df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
Suppose I need column 'b'
to be at the end. I could do:
df[['a', 'c', 'd', 'b']]
But what is the most efficient way to ensure that a given column is at the end?
This is what I've been going with. What would others do?
def put_me_last(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
put_me_last(df, 'b')
Timing Results
conclusion
mfripp is the winner. Seems as if reindex_axis
is a large efficiency gain over []
. That is really good info.
code
from string import lowercase
df_small = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('abcd'))
df_large = pd.DataFrame(np.arange(1000000).reshape(10000, 100),
columns=pd.MultiIndex.from_product([list(lowercase[:-1]), ['One', 'Two', 'Three', 'Four']]))
def pir1(df, column):
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def pir2(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
return df[np.roll(df.columns, len(df.columns) - 1 - pos)]
def pir3(df, column):
if df.columns[-1] == column:
return df
else:
pos = df.columns.values.__eq__('b').argmax()
cols = df.columns.values
np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])
return df[np.concatenate([cols[:pos], cols[1+pos:], cols[[pos]]])]
def pir4(df, column):
if df.columns[-1] == column:
return df
else:
return df[np.roll(df.columns.drop(column).insert(0, column), -1)]
def carsten1(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
return pd.concat([df.drop(column, axis=1), df[column]], axis=1)
def carsten2(df, column):
cols = list(df)
if cols[-1] == column:
return df
else:
idx = cols.index(column)
new_cols = cols[:idx] + cols[idx + 1:] + [column]
return df[new_cols]
def mfripp1(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df[new_cols]
def mfripp2(df, column):
new_cols = [c for c in df.columns if c != column] + [column]
return df.reindex_axis(new_cols, axis='columns', copy=False)
def ptrj1(df, column):
return df.reindex(columns=df.columns.drop(column).append(pd.Index([column])))
def shivsn1(df, column):
column_list=list(df)
column_list.remove(column)
column_list.append(column)
return df[column_list]
def merlin1(df, column):
return df[df.columns.drop(["b"]).insert(99999, 'b')]
list_of_funcs = [pir1, pir2, pir3, pir4, carsten1, carsten2, mfripp1, mfripp2, ptrj1, shivsn1]
def test_pml(df, pml):
for c in df.columns:
pml(df, c)
summary = pd.DataFrame([], [f.__name__ for f in list_of_funcs], ['Small', 'Large'])
for f in list_of_funcs:
summary.at[f.__name__, 'Small'] = timeit(lambda: test_pml(df_small, f), number=100)
summary.at[f.__name__, 'Large'] = timeit(lambda: test_pml(df_large, f), number=10)