Here is my bincount
solution
Data
Note that this is different from OP's to point out that it works as expected.
list a b c
0 1 5 1 1
1 11 11 2 7
2 0 0 0 0
3 9 5 9 5
4 8 8 2 7
Solution
v = df.values[:, 1:]
f, u = pd.factorize([(i, e) for i, row in enumerate(v) for e in row])
counts = np.bincount(f)[f].reshape(v.shape)
x = (counts == counts.max(1, keepdims=1)).argmax(1)
y = np.arange(v.shape[0])
df.assign(d=v[y, x])
list a b c d
0 1 5 1 1 1
1 11 11 2 7 11
2 0 0 0 0 0
3 9 5 9 5 5
4 8 8 2 7 8
Details
Get numpy array of just the values we want.
v = df.values[:, 1:]
Use enumerate
and comprehension to create a list of tuples. Each rows values will be distinct from other rows because I'm placing an identifier in the first position of the tuple for each row. Namely the value from enumerate. I then pass these into Pandas' factorize
function in order to place into Numpy's bincount
.
f, u = pd.factorize([(i, e) for i, row in enumerate(v) for e in row])
Now I use bincount
on f
and slice it with f
to get an array of the same size, but now filled with count values.
counts = np.bincount(f)[f].reshape(v.shape)
I locate the maximum values and slice the original array to get what those values where.
x = (counts == counts.max(1, keepdims=1)).argmax(1)
y = np.arange(v.shape[0])
Note that if all values are the same or if there are multiple modes, argmax
will pick the first one. When all are the same, this is column a
.
df.assign(d=v[y, x])