python - 计算满足条件的所有行的最小距离

标签 python pandas

我在 python 中使用 pandas 并想执行以下操作: 我想在我的数据框中引入一个新的 A 列。为了计算它,我想考虑 B 列中的所有行与 B 列中的“当前元素”(我认为这是我现在卡住的部分)具有相同的值,然后取 C 列的最小值减去所有这些C的当前元素的值-并排除差异0,即自引用。

举个例子:

   B  C    A
0  0  1.2  1.7  (calculation: possible rows are 1 and 2 (all have B = 0), the differences are 2.9 - 1.2 and 3.0 - 1.2 => min = 1.7
1  0  2.9  -1.7 (min difference is 1.2 - 2.9)
2  0  3.0  -1.8
3  1  4.1  1.4
4  1  5.5  -1.4

谢谢!

最佳答案

这很难理解,但是工作...

df['new'] = df.B.map(df.groupby('B').C.apply(list))

df.apply(lambda x :min(list(map(lambda y: y - x['C'],list(set(x['new'])-set([x['C']]))))),axis=1)


Out[1013]: 
0    1
1   -1
2   -2
3    1
4   -1
dtype: int64

更多信息:

df['NewA']=df.apply(lambda x :min(list(map(lambda y: y - x['C'],list(set(x['new'])-set([x['C']]))))),axis=1)
df
Out[1015]: 
   B  C  A        new  NewA
0  0  1  1  [1, 2, 3]     1
1  0  2 -1  [1, 2, 3]    -1
2  0  3 -2  [1, 2, 3]    -2
3  1  4  1     [4, 5]     1
4  1  5 -1     [4, 5]    -1

让我们使用 numpy 方法

A = df.C.values[:, None] - df.C.values.T
np.fill_diagonal(A, 9999999)
G=df.groupby('B')
np.concatenate([np.min(A[y.min():y.max()+1,y.min():y.max()+1],0) for _, y in G.groups.items()])

时间

%timeit df.apply(lambda x: df[(df.B == x.B) & (~df.C.eq(x.C))].min().C - x.C, axis=1)
100 loops, best of 3: 4.14 ms per loop
%timeit df.groupby('B')['C'].transform(lambda x: np.where(x.idxmin() == x.index,1,(x[x.idxmin()] - x)))
100 loops, best of 3: 1.67 ms per loop

def fff(x):
    A = df.C.values[:, None] - df.C.values.T
    np.fill_diagonal(A, 9999999)
    G=df.groupby('B')
    np.concatenate([np.min(A[y.min():y.max()+1,y.min():y.max()+1],0) for _, y in G.groups.items()])
%timeit fff(1)
1000 loops, best of 3: 758 µs per loop

关于python - 计算满足条件的所有行的最小距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47576632/

相关文章:

python - 如何将多列添加到 DataFrame?

python - 使用 Python 从 Google Drive/Workspace 下载电子表格

python - 我应该在函数内部编写函数还是将它们全部写在全局框架中?

Python Twisted,SSL 超时错误

python - 跨行执行聚合函数(例如平均值)会产生 NaN

python - 无法将 Json 转换为 Pandas 数据框

python - 如何获取请求参数并返回django Rest-framework

python - Django 将表迁移到新数据库

python - pandas groupby 无法正确计数。为什么?

python - 如何更改行尾约定?