Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Columns from one dataframe with columns from another dataframe in pandas

I have two DataFrame, let's call it X and Y, with dimension of X being 2063 x 14 and dimension of Y being 2063 x 8. I want to replace column 4 to 12 of X with Y, can I do that in pandas?

The solution I found so far are replacing certain values from a column/multiple columns, but not entire DataFrame at once. Appreciate any help. (:

like image 915
Guo Xian Yau Avatar asked Jun 30 '16 00:06

Guo Xian Yau


People also ask

How do I copy a column from one DataFrame to another panda?

Using DataFrame. Pandas. DataFrame. copy() function returns a copy of the DataFrame. Select the columns from the original DataFrame and copy it to create a new DataFrame using copy() function.

How do you replace a part of a DataFrame with another DataFrame?

To replace values of a DataFrame with the value of another DataFrame, use the replace() method n Pandas.


1 Answers

This should work:

X.iloc[:, 4:12] = Y

iloc and loc allow us to both slice from and assign to slices of a dataframe.

#            assign Y
#                |
#               /-\
X.iloc[:, 4:12] = Y
#      ^   ^
#      |   |
# slices   |
# all rows |
#          slices columns
#          5 through 12
#          which constitute
#          the 8 columns we want
#          replace with the 8
#          columns of Y
like image 79
piRSquared Avatar answered Sep 26 '22 17:09

piRSquared