python - 将 pandas DataFrame 行复制到多个其他行

标签 python pandas

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

我看的问题如下:

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

最佳答案

使用 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

关于python - 将 pandas DataFrame 行复制到多个其他行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875648/

相关文章:

python - 如何在Django中访问上传的文件?

python - np.logic_or 与reduce 返回不同的结果

python - 我们如何将新数据写入现有的 Excel 电子表格?

python - 从时间序列中提取 Pandas 中的每月分类(虚拟)变量

python - 无法使用套接字获取所需内容

python - 从 args 动态设置 pytest fixture 的范围

python - 如何替换 SQLAlchemy 映射器已弃用的 "order_by"选项?

python - 使用 PIL 保存图像但图像无法打开

python - 数据帧 : how do I find value in one column for a quantile in a second column

python - 读取 excel 时 pandas 出现 AssertionError