根据布尔V组合2个Pandas数据帧

2024-09-30 01:37:03 发布

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

我的问题是:
假设我在pandas中有两个列数相同的数据帧,例如:

A= 1 2
   3 4 
   8 9

以及

^{pr2}$

还有一个布尔向量,长度正好是A+numofb rows=5,其中的1与B中的rows num相同,在这个例子中意味着两个1。 假设Bool= 0 1 0 1 0。在

我的目标是将A和B合并到一个称为C的更大的数据帧中,使B的行与Bool中的1相对应,因此在这个示例中它将给出:

C= 1 2
   7 8
   3 4 
   4 0
   8 9

你知道怎么做吗? 如果你知道这对我有多大的帮助。 谢谢你的阅读。在


Tags: 数据示例目标pandas向量num例子rows
3条回答

一种方法是创建一个具有预期形状的空数据帧,然后将AB中的值填充到:

import pandas as pd
import numpy as np

# initialize a data frame with the same data types as A thanks to @piRSquared
df = pd.DataFrame(np.empty((A.shape[0] + B.shape[0], A.shape[1])), dtype=A.dtypes)
Bool = np.array([0, 1, 0, 1, 0]).astype(bool)

df.loc[Bool,:] = B.values
df.loc[~Bool,:] = A.values

df
#   0   1
#0  1   2
#1  7   8
#2  3   4
#3  4   0
#4  8   9

这是一个只支持pandas的解决方案,它可以重新索引原始数据帧,然后将它们连接起来:

Bool = pd.Series([0, 1, 0, 1, 0], dtype=bool) 
B.index = Bool[ Bool].index
A.index = Bool[~Bool].index
pd.concat([A,B]).sort_index() # sort_index() is not really necessary
#   0  1
#0  1  2
#1  7  8
#2  3  4
#3  4  0
#4  8  9

下面的方法将推广到大于2的组。从开始

A = pd.DataFrame([[1,2],[3,4],[8,9]])    
B = pd.DataFrame([[7,8],[4,0]])    
C = pd.DataFrame([[9,9],[5,5]])
bb = pd.Series([0, 1, 0, 1, 2, 2, 0])

我们可以利用

^{pr2}$

这给了

^{3}$

{然后按顺序排列它们的值。这意味着我们可以得到

In [270]: pd.Series([1, 0, 0, 1, 0]).rank(method='first')
Out[270]: 
0    4.0
1    1.0
2    2.0
3    5.0
4    3.0
dtype: float64

这正是我们要选择行的iloc顺序(减去1之后)。在

相关问题 更多 >

    热门问题