user6521287
user6521287

Reputation:

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. (:

Upvotes: 5

Views: 4100

Answers (1)

piRSquared
piRSquared

Reputation: 294546

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

Upvotes: 5

Related Questions