简体   繁体   English

查找最接近的值对并在Python中计算均值

[英]Find closest value pairs and calculate mean in Python

I have a dataframe as follows: 我有一个数据框,如下所示:

import pandas as pd
import numpy as np
import random

np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(100, 3)), 
                  columns=list('ABC'), 
                  index=['{}'.format(i) for i in range(100)])

ix = [(row, col) for row in range(df.shape[0]) for col in range(df.shape[1])]
for row, col in random.sample(ix, int(round(.1*len(ix)))):
    df.iat[row, col] = np.nan

df = df.mask(np.random.random(df.shape) < .05)  #insert 5% of NaNs  

df.head()

    A   B   C
0  99  78  61
1  16  73   8
2  62  27  30
3  80   7  76
4  15  53  80

If I want find closest value pairs from columns A, B and C , and calculate mean of pairs value as column D ? 如果我想从columns A, B and C找到最接近的值对,并计算值对的平均值作为column D How could I do that in Pandas? 我该如何在熊猫中做到这一点? Thanks. 谢谢。

Since my real data has some NaNs , if some rows have only two values, then calculate their means as columns D , if some rows only has one value, then take that value in column D . 由于我的真实数据具有某些NaNs ,因此,如果某些行仅具有两个值,则将其均值计算为columns D ;如果某些行仅具有一个值,则将其取入column D

I have tried with calculating absolute value of each pairs, find smallest values from columns diffAB, diffAC and diffBC , then calculate means of smallest pairs means, but I think maybe there is better to do that. 我尝试过计算每对的绝对值,从columns diffAB, diffAC and diffBC找到最小值,然后计算最小对的均值,但我认为这样做更好。

cols = ['A', 'B', 'C']
df[cols]=df[cols].fillna(0)

df['diffAB'] = (df['A'] - df['B']).abs()
df['diffAC'] = (df['A'] - df['C']).abs()
df['diffBC'] = (df['B'] - df['C']).abs()

Update: 更新:

df['Count'] = df[['A', 'B', 'C']].apply(lambda x: sum(x.notnull()), axis=1)

if df['Count'] == 3:
    def meanFunc(row):
        minDiffPairIndex = np.argmin( [abs(row['A']-row['B']), abs(row['B']-row['C']), abs(row['C']-row['A']) ])      
        meanDict = {0: np.mean([row['A'], row['B']]), 1: np.mean([row['B'], row['C']]), 2: np.mean([row['C'], row['A']])}
        return meanDict[minDiffPairIndex]
if df['Count'] == 2:
    ...

Expected result: 预期结果:

    A   B   C   D
0  99  78  61  69.5
1  16  73   8   12
2  62  27  30  28.5
3  80   7  76   78
4  15  53  80  66.5

I'd use numpy here: 我在这里使用numpy:

In [11]: x = df.values

In [12]: x.sort()

In [13]: (x[:, 1:] + x[:, :-1])/2
Out[13]:
array([[69.5, 88.5],
       [12. , 44.5],
       [28.5, 46. ],
       [41.5, 78. ],
       [34. , 66.5]])

In [14]: np.diff(x)
Out[14]:
array([[17, 21],
       [ 8, 57],
       [ 3, 32],
       [69,  4],
       [38, 27]])

In [15]: np.diff(x).argmin(axis=1)
Out[15]: array([0, 0, 0, 1, 1])

In [16]: ((x[:, 1:] + x[:, :-1])/2)[np.arange(len(x)), np.diff(x).argmin(axis=1)]
Out[16]: array([69.5, 12. , 28.5, 78. , 66.5])

In [17]: df["D"] = ((x[:, 1:] + x[:, :-1])/2)[np.arange(len(x)), np.diff(x).argmin(axis=1)]

This may not be the fastest way of doing this but it's very straightforward. 这可能不是最快的方法,但是非常简单。

def func(x):
    a,b,c = x
    diffs = np.abs(np.array([a-b,a-c,b-c]))
    means = np.array([(a+b)/2,(a+c)/2,(b+c)/2])
    return means[diffs.argmin()]

df["D"] = df.apply(func,axis=1)
df.head()

Assuming that you require an additional column D having the mean of the value pair which has the least difference among the three possible pairs: (colA, colB), (colB, colC) and (colC, colA) , following code should work: 假设您需要具有值对平均值的附加column D ,该值对在(colA, colB), (colB, colC) and (colC, colA)这三种可能的对中具有最小的差异,以下代码应该可以工作:

Updated: 更新:

def meanFunc(row):    
    nonNanValues = [x for x in list(row) if str(x) != 'nan']
    numOfNonNaN = len(nonNanValues) 
    if(numOfNonNaN == 0): return 0
    if(numOfNonNaN == 1): return nonNanValues[0]
    if(numOfNonNaN == 2): return np.mean(nonNanValues)
    if(numOfNonNaN == 3):
        minDiffPairIndex = np.argmin( [abs(row['A']-row['B']), abs(row['B']-row['C']), abs(row['C']-row['A']) ])      
        meanDict = {0: np.mean([row['A'], row['B']]), 1: np.mean([row['B'], row['C']]), 2: np.mean([row['C'], row['A']])}
        return meanDict[minDiffPairIndex]

df['D'] = df.apply(meanFunc, axis=1)

Above code handles the NaN values in rows in the way that if all three values are NaN then column D has value 0 , if two values are NaN then non-NaN value is assigned to column D and if there exists exactly one NaN then the mean of remaining two is assigned to column D . 上面的代码以以下方式处理行中的NaN值:如果所有三个值均为NaNcolumn D值为0 ;如果两个值为NaN则将非NaN值分配给column D ;如果正好存在一个NaN则均值其余两个中的第一个分配给column D

Previous: 以前:

def meanFunc(row):
    minDiffPairIndex = np.argmin( [abs(row['A']-row['B']), abs(row['B']-row['C']), abs(row['C']-row['A']) ])      
    meanDict = {0: np.mean([row['A'], row['B']]), 1: np.mean([row['B'], row['C']]), 2: np.mean([row['C'], row['A']])}
    return meanDict[minDiffPairIndex]

df['D'] = df.apply(meanFunc, axis=1)

Hope I understood your question correctly. 希望我能正确理解您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM