How to rearrange columns in a data set, so that one specific column appears before another?

63 views Asked by At

I am completely new to pandas, and python in general. I have a dataset, containing 18 columns. In the 10th column, I have "temp_c" representing temperatures in celsius, and in the 17th column, I have "temp_f" representing temperatures in fahrenheit. How do I select the temp_f and reposition it so that it will now appear in front of temp_c?

I'm attempting this in Jupyter notebook, but to no avail. I simply don't have enough experience to better articulate this question/problem.

df.sort_values('temp_f' , 'temp_c')
5

There are 5 answers

0
SomeDude On

You can get locations of temp_c and temp_f using get_loc and swap the columns

c = df.columns.get_loc('temp_c')
f = df.columns.get_loc('temp_f')
cols = df.columns.tolist()
temp = cols[c+1] if c < len(cols)-1 else None
if temp:
    cols[c+1] = cols[f]
    cols[f] = temp
df = df[cols]
0
Michael Cao On

You can display the columns in your chosen order using df[['temp_f', 'temp_c']]

0
Max Bileschi On
current_columns = df.columns.tolist()
new_columns = [...] # reorder your columns however you want,
                    # based on current_columns.

df = df[new_columns]
0
kaispace30098 On

one easy way is you redefine your dataframe. let's say your data frame is df then you can print out the column names

print(df.columns)

next, you copy the string in the bracket in the result, and change the columns you want to swich, for example ['1',...'17','18',...] to ['1',...'18','17',...] and redefine your dataframe:

df=df[['1',...'18','17',...]]
0
mozway On

One possibility using insert and pop:

idx_c = df.columns.get_loc('temp_c')
idx_f = df.columns.get_loc('temp_f')

df.insert(idx_c-(idx_f<idx_c), 'temp_f', df.pop('temp_f'))

print(df)

Output:

  col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8 col_9 temp_f temp_c col_11  \
0   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN    NaN    NaN    NaN   

  col_12 col_13 col_14 col_15 col_16  
0    NaN    NaN    NaN    NaN    NaN