将pandas数据帧行复制到多个其他行

2024-05-18 23:33:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我看了一下下面的问题:

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

Tags: columnsofto数据infromdataframepandas
2条回答

假设您必须将某些行和列从data frame复制到另一个数据frame,这样做。 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

使用loc并传递一个感兴趣的索引标签列表,在下面的逗号后面,:表示要设置所有列值,然后分配序列,但调用属性.values,这样它就是一个numpy数组。否则,您将得到一个ValueError,因为将有一个形状不匹配,因为您打算用一行覆盖两行,如果是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

相关问题 更多 >

    热门问题