Pandas Apply - 返回多行

B_M*_*ner 2 python pandas dask

我有两个数据框,我需要比较行的完整组合并返回符合条件的组合.事实证明,对于我们的小型集群来说Spark(使用交叉连接)过于密集,所以我正在尝试这种方法,最终会看到是否Dask可以改进它.

如果表A和B是

a=pd.DataFrame(np.array([[1,2,3],[4,5,6]]), columns=['a','b','c'])

b=pd.DataFrame(np.array([[4,7,4],[6,5,1],[8,6,0]]), columns=['d','e','f'])
Run Code Online (Sandbox Code Playgroud)

然后所有组合看起来像这样,其中计算AD.假设我只想保留AD> = - 3的行

A   B   C   D   E   F   A-D
1   2   3   4   7   4   -3
1   2   3   6   5   1   -5
1   2   3   8   6   0   -7
4   5   6   4   7   4   0
4   5   6   6   5   1   -2
4   5   6   8   6   0   -4
Run Code Online (Sandbox Code Playgroud)

我尝试使用apply执行此操作,但似乎我无法返回dataframe函数的多行(该函数创建'A'的单行和'B'的整个表的所有组合并返回行符合标准.

这是我测试的功能:

def return_prox_branches(a, B, cutthresh):

    aa=a['a']-B['d']

    keep_B = B.copy().loc[(aa.values >= cutthresh),:]

    keep_B['A']=a['a']

    keep_B['B']=a['b']

    keep_B['C']=a['c']

    keep_B['A-D']=a['a']-keep_B['d']

    print(keep_B)

    return(keep_B)



a.apply(return_prox_branches, axis=1, args=(b,-3))





ValueError: cannot copy sequence with size 7 to array axis with dimension 1
Run Code Online (Sandbox Code Playgroud)

实际上,这两个表是数百万行.

有没有办法让大熊猫有效地工作?

piR*_*red 5

有趣的方式!

以这种方式解压缩成为可能的Python 3.5
https://www.python.org/dev/peps/pep-0448/#rationale

i, j = np.where(np.subtract.outer(a.a, b.d) >= -3)
pd.DataFrame({**a.iloc[i].to_dict('l'), **b.iloc[j].to_dict('l')})

   a  b  c  d  e  f
0  1  2  3  4  7  4
1  4  5  6  4  7  4
2  4  5  6  6  5  1
Run Code Online (Sandbox Code Playgroud)

相似但不那么令人困惑

i, j = np.where(np.subtract.outer(a.a, b.d) >= -3)
a_ = a.values[i]
b_ = b.values[j]

d = pd.DataFrame(
    np.column_stack([a_, b_]),
    columns=a.columns.append(b.columns)
)

d

   a  b  c  d  e  f
0  1  2  3  4  7  4
1  4  5  6  4  7  4
2  4  5  6  6  5  1
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我们依赖于b.dfrom 的外部减法a.a.这将创建一个二维数组,其中包含值的每个可能的减法b.da.a. np.where找到这个差异所在的坐标>= -3.我可以使用这些结果来切割原始数据帧并将它们放在一起.


纯净的(ish)熊猫

我怀疑你可以用dask来使用它

def gen_pseudo(d_):
    def pseudo(d):
        cols = d.columns.append(d_.columns)
        return d_.assign(**d.squeeze()).query('a - d >= -3')[cols]
    return pseudo

a.groupby(level=0).apply(gen_pseudo(b))

     a  b  c  d  e  f
0 0  1  2  3  4  7  4
1 0  4  5  6  4  7  4
  1  4  5  6  6  5  1
Run Code Online (Sandbox Code Playgroud)

非封闭替代方案

def pseudo(d, d_):
    cols = d.columns.append(d_.columns)
    return d_.assign(**d.squeeze()).query('a - d >= -3')[cols]

a.groupby(level=0).apply(pseudo, d_=b)
Run Code Online (Sandbox Code Playgroud)

理解

ja = a.columns.get_loc('a')
jb = b.columns.get_loc('d')

pd.DataFrame([
    np.append(ra, rb)
    for ra in a.values
    for rb in b.values
    if ra[ja] - rb[jb] >= -3
], columns=a.columns.append(b.columns))

   a  b  c  d  e  f
0  1  2  3  4  7  4
1  4  5  6  4  7  4
2  4  5  6  6  5  1
Run Code Online (Sandbox Code Playgroud)