将pandas DataFrame行复制到其他多个行 [英] Copy pandas DataFrame row to multiple other rows
问题描述
简单实用的问题,但我找不到解决方法.
Simple and practical question, yet I can't find a solution.
我看的问题如下:
复制列的最快方法从一个DataFrame到另一个使用Pandas的数据框架?
这些和我的主要区别在于,我不需要插入单个值,而是插入一行.
The key difference between those and mine is that I need not to insert a single value, but a row.
我的问题是,我拿起一行数据框,例如df1
.因此,我有一个系列.
My problem is, I pick up a row of a dataframe, say df1
. Thus I have a series.
现在我有了另一个数据框df2
,我已经根据一个条件选择了多行,我想将该系列复制到所有这些行.
Now I have this other dataframe, df2
, that I have selected multiple rows according to a criteria, and I want to replicate that series to all those row.
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]行中.像这样的无效代码:
What I want to accomplish is inserting df1[3] into the lines df2[2] and df3[3] for example. So something like the non working code:
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
,那么它将无法按照您的意愿对齐:
Use loc
and pass a list of the index labels of interest, after the following comma the :
indicates we want to set all column values, we then assign the series but call attribute .values
so that it's a numpy array. Otherwise you will get a ValueError
as there will be a shape mismatch as you're intending to overwrite 2 rows with a single row and if it's a Series
then it won't align as you desire:
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
这篇关于将pandas DataFrame行复制到其他多个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!