Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new column between other dataframe columns [duplicate]

Tags:

dataframe

r

I want to add a new column with "NA"s in my dataframe:

     A       B
1    14379  32094
2   151884  174367
3   438422  449382

But I need it to be located between col. A and B, like this:

     A       C      B
1    14379   NA    32094
2   151884   NA    174367
3   438422   NA    449382

I know how to add col. C after col. B, but that is not helpful to me... Anyone know how to do it?

like image 653
TWest Avatar asked Apr 11 '13 19:04

TWest


People also ask

How do you add a column to a DataFrame based on another column?

Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.

How do you add a column to a DataFrame to another data frame?

After extraction, the column needs to be simply added to the second dataframe using join() function. This function needs to be called with reference to the dataframe in which the column has to be added and the variable name which stores the extracted column name has to be passed to it as the argument.

Can DataFrame have duplicate columns?

To find duplicate columns we need to iterate through all columns of a DataFrame and for each and every column it will search if any other column exists in DataFrame with the same contents already. If yes then that column name will be stored in the duplicate column set.

How do I combine two DataFrame columns?

By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame.


1 Answers

In 2 steps, you can reorder the columns:

dat$C <- NA
dat <- dat[, c("A", "C", "B")]
         A  C          B
1  0.596068 NA -0.7783724
2 -1.464656 NA -0.8425972

You can also use append

dat <- data.frame(A = rnorm(2), B = rnorm(2))
as.data.frame(append(dat, list(C = NA), after = 1))

           A   C          B
1 -0.7046408  NA  0.2117638
2  0.8402680  NA -2.0109721
like image 56
agstudy Avatar answered Oct 16 '22 01:10

agstudy