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

时间:2016-04-26 21:00:15

标签: 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

2 个答案:

答案 0 :(得分:11)

使用:并传递感兴趣的索引标签列表,在以下逗号后.values表示我们要设置所有列值,然后我们分配系列但调用属性{{1所以它是一个numpy数组。否则你会得到一个ValueError因为你打算用一行覆盖2行,如果它是一个Series,那么就会出现形状不匹配,那么它就不会按你的意愿对齐:< / p>

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

答案 1 :(得分:1)

假设您必须将某些行和列从数据框复制到另一个数据框执行此操作。     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
相关问题