Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one reorder columns in a data frame?

How would one change this input (with the sequence: time, in, out, files):

Time   In    Out  Files 1      2     3    4 2      3     4    5 

To this output (with the sequence: time, out, in, files)?

Time   Out   In  Files 1      3     2    4 2      4     3    5 

Here's the dummy R data:

table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5)) table ##  Time In Out Files ##1    1  2   3     4 ##2    2  3   4     5 
like image 775
Catherine Avatar asked Apr 11 '11 11:04

Catherine


People also ask

How do you reorder a data frame?

Reordering or Rearranging the column of dataframe in pandas python can be done by using reindex function. In order to reorder or rearrange the column in pandas python. We will be different methods. To reorder the column in ascending order we will be using Sort() function.

How do you change the order of columns in Python?

You can change the order of the dataframe columns using the reindex() method. The reindex() method accepts columns as a list. Pass the columns as list in the order of how you want to rearrange them.

How do I reorder columns in spark DataFrame?

In order to Rearrange or reorder the column in pyspark we will be using select function. To reorder the column in ascending order we will be using Sorted function. To reorder the column in descending order we will be using Sorted function with an argument reverse =True. We also rearrange the column by position.

How do I reorder rows and columns in pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.


1 Answers

Your dataframe has four columns like so df[,c(1,2,3,4)]. Note the first comma means keep all the rows, and the 1,2,3,4 refers to the columns.

To change the order as in the above question do df2[,c(1,3,2,4)]

If you want to output this file as a csv, do write.csv(df2, file="somedf.csv")

like image 186
richiemorrisroe Avatar answered Oct 26 '22 09:10

richiemorrisroe