Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new column to a dataframe using matching values of another dataframe [duplicate]

Tags:

I am trying to fill in table1 with matching val2 values of table2

table1$New_val2 = table2[table2$pid==table1$pid,]$val2 

enter image description here

But I get the warning

longer object length is not a multiple of shorter object length 

which is fair enough because the table lengths are not the same.

Please kindly direct me on the correct way to do this.

like image 648
andy Avatar asked May 04 '16 17:05

andy


People also ask

How do you create a new column in a DataFrame with the same value?

df = df. assign(col_name=[value1, value2, value3, ...]) And you can use the insert() function to add a new column to a specific location in a pandas DataFrame: df.

Which function is used to add additional columns in a DataFrame?

Using assign() DataFrame. assign() method can be used when you need to insert multiple new columns in a DataFrame, when you need to ignore the index of the column to be added or when you need to overwrite the values of an existing columns.


2 Answers

merge(table1, table2[, c("pid", "val2")], by="pid")

Add in the all.x=TRUE argument in order to keep all of the pids in table1 that don't have matches in table2...

You were on the right track. Here's a way using match...

table1$val2 <- table2$val2[match(table1$pid, table2$pid)]

like image 50
cory Avatar answered Oct 24 '22 12:10

cory


I am not sure if you mean this but you might use:

newtable <- merge(table1,table2, by  = "pid")  

This will create a new table called newtable, with 3 columns and those values matched by the id, in this case "pid".

like image 44
adrian1121 Avatar answered Oct 24 '22 13:10

adrian1121