【问题标题】:Copy pandas DataFrame row to multiple other rows将 pandas DataFrame 行复制到其他多行
【发布时间】:2016-08-20 21:56:53
【问题描述】:

简单实用的问题,但我找不到解决方案。

我看过的问题如下:

Modifying a subset of rows in a pandas dataframe

Changing certain values in multiple columns of a pandas DataFrame at once

Fastest way to copy columns from one DataFrame to another using pandas?

Selecting with complex criteria from pandas.DataFrame

这些和我的主要区别在于我不需要插入单个值,而是插入一行。

我的问题是,我拿起一行数据框,比如df1。所以我有一个系列。

现在我有了另一个数据框df2,我根据标准选择了多行,我想将该系列复制到所有这些行。

df1:

Index/Col   A   B  C
1           0   0  0
2           0   0  0
3           1   2  3
4           0   0  0

df2:

Index/Col   A   B  C
1           0   0  0
2           0   0  0
3           0   0  0
4           0   0  0

例如,我想要完成的是将 df1[3] 插入 df2[2] 和 df3[3] 行。所以类似于非工作代码:

series = df1[3]
df2[df2.index>=2 and df2.index<=3] = series

返回

df2:

Index/Col   A   B  C
1           0   0  0
2           1   2  3
3           1   2  3
4           0   0  0

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用loc并传递感兴趣的索引标签列表,在下面的逗号之后:表示我们要设置所有列值,然后我们分配系列但调用属性.values使其成为numpy 数组。否则,您将获得 ValueError,因为您打算用单行覆盖 2 行,而形状不匹配,如果是 Series,则它不会按照您的意愿对齐:

    In [76]:
    df2.loc[[2,3],:] = df1.loc[3].values
    df2
    
    Out[76]:
       A  B  C
    1  0  0  0
    2  1  2  3
    3  1  2  3
    4  0  0  0
    

    【讨论】:

      【解决方案2】:

      假设您必须将某些行和列从数据框复制到另一个数据框,请执行此操作。 code

          df2 = df.loc[x:y,a:b]   // x and y are rows bound and a and b are column 
                                      bounds that you have to select
      

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        • 2019-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 1970-01-01
        相关资源
        最近更新 更多