-1

When I add a column df[xx] it is added at the end of the dataframe

What I would like to do is add the column "xx" right after column "x" ("x" could be anywhere in the dataframe) Is there an easy way to do this?

cs95
  • 379,657
  • 97
  • 704
  • 746
Padma
  • 37
  • 1
  • 3
  • Possible duplicate of [Python Pandas - Re-ordering columns in a dataframe based on column name](https://stackoverflow.com/q/11067027/1278112) – Shihe Zhang Oct 28 '17 at 02:09

1 Answers1

1
df = pd.DataFrame(columns=['x', 'y', 'xx'])
df
x   y   xx


df = df.reindex_axis(sorted(df.columns), axis=1)
df
x   xx  y

EDIT:

df = pd.DataFrame(columns=['x', 'y', 'xx', 'q', 'q1'])
row = pd.Series({'x':1,'y':2,'xx':3,'q':4,'q1':5})
df = df.append(row, ignore_index=True)
df

   x    y   xx  q   q1
0   1   2   3   4   5

df = df.reindex_axis(['q', 'y', 'x', 'xx', 'q1'], axis=1)
   q    y   x   xx  q1
0   4   2   1   3   5
Mikell-S
  • 42
  • 3
  • Yes this would work, If I wanted to enumerate all the columns, I have about 45 columns; I want a add a column next to another column "Q" with some manipulation of the values in column Q. Df [Q1] will add the column Q1 at the end; it will not put it after column Q. Also am not planning to sort the columns. I can add to the end or beginning, but inserting in the middle without enumerating the entire list (df.columns) is where i am having an issue – Padma Oct 28 '17 at 05:05
  • df.reindex_axis takes in a list, so you can prepare the list or change it with a function as you add new columns, but I think that would help. See my edits – Mikell-S Oct 28 '17 at 11:51
  • Thanks! This does mean enumerating all the columns and rearranging them; It is hard if I have 50 columns:-) – Padma Oct 28 '17 at 13:16