【问题标题】:Replacing Columns from one dataframe with columns from another dataframe in pandas用熊猫中另一个数据框的列替换一个数据框的列
【发布时间】:2023-04-03 16:55:02
【问题描述】:

我有两个 DataFrame,我们称它为 X 和 Y,X 的尺寸为 2063 x 14,Y 的尺寸为 2063 x 8。我想用 Y 替换 X 的第 4 到 12 列,我可以这样做吗熊猫?

到目前为止,我发现的解决方案是从一列/多列中替换某些值,而不是一次替换整个 DataFrame。感谢任何帮助。 (:

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    这应该可行:

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

    iloc 和 loc 允许我们对数据帧的切片进行切片和分配。

    #            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
    

    【讨论】:

    • 为什么?为什么它有效?您能否在答案中添加一些上下文?
    • @ppperry 公平批评。我现在将添加一些上下文。
    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2019-12-21
    • 2019-06-30
    • 2017-11-01
    相关资源
    最近更新 更多