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
? 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
.
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.
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:
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:
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.