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

Time:01-27

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')

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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

df = df[new_columns]

CodePudding user response:

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',...]]
  • Related