3

I have a two dataframes as follows:

df1:

 A B C D E 0 8 6 4 9 7 1 2 6 3 8 5 2 0 7 6 5 8 

df2:

 M N O P Q R S T 0 1 2 3 1 4 5 6 2 7 8 9 3 8 6 5 4 5 4 3 

I have taken out a slice of data from df1 as follows:

>data_1 = df1.loc[0:1] >data_1 A B C D E 0 8 6 4 9 7 1 2 6 3 8 5 

Now I need to insert this data_1 into df2 at specific location of Index(0,P) (row,column). Is there any way to do it? I do not want to disturb the other columns in df2.

I can extract individual values of each cell and do it but since I have to do it for a large dataset, its not possible to do it cell-wise.

Cellwise method:

>var1 = df1.iat[0,1] >var2 = df1.iat[0,0] >df2.at[0, 'P'] = var1 >df2.at[0, 'Q'] = var2 

2 Answers 2

3

If you specify all the columns, it is possible to do it as follows:

df2.loc[0:1, ['P', 'Q', 'R', 'S', 'T']] = df1.loc[0:1].values 

Resulting dataframe:

 M N O P Q R S T 0 1 2 3 8.0 6.0 4.0 9.0 7.0 1 4 5 6 2.0 6.0 3.0 8.0 5.0 2 7 8 9 3 8 6 5 4 5 4 3 
Sign up to request clarification or add additional context in comments.

Comments

2

You can rename columns and index names for match to second DataFrame, so possible use DataFrame.update for correct way specifiest by tuple pos:

data_1 = df1.loc[0:1] print (data_1) A B C D E 0 8 6 4 9 7 1 2 6 3 8 5 pos = (2, 'P') data_1 = data_1.rename(columns=dict(zip(data_1.columns, df2.loc[:, pos[1]:].columns)), index=dict(zip(data_1.index, df2.loc[pos[0]:].index))) print (data_1) P Q R S T 2 8 6 4 9 7 3 2 6 3 8 5 df2.update(data_1) print (df2) M N O P Q R S T 0 1 2 3 NaN NaN NaN NaN NaN 1 4 5 6 NaN NaN NaN NaN NaN 2 7 8 9 8.0 6.0 4.0 9.0 7.0 3 8 6 5 2.0 6.0 3.0 8.0 5.0 4 5 4 3 NaN NaN NaN NaN NaN 

How working rename - idea is select all columns and all index values after specified column, index name by loc and then zip by columns names of data_1 with convert to dictionary. So last replace bot, index and columns names in data_1 by next columns, index values.

1 Comment

Thanks, this works like a charm. Could you please elaborate more on the data_1.rename code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.