Skip to content Skip to sidebar Skip to footer

Dataframe: How To Select For Each Row Different Column

Let's consider a dataframe A with three columns: a, b and c. Suppose we have also Series B of the the same size as A. In each row it contains the name of one of the A's column. I w

Solution 1:

You can use DataFrame.lookup:

pd.Series(A.lookup(B.index, B), index=B.index)

0    5
1    7
2    8
3    7
4    8
dtype: int64

A NumPy solution involving broadcasting is:

A.values[B.index, (A.columns.values == B[:, None]).argmax(1)]
# array([5, 7, 8, 7, 8])

Post a Comment for "Dataframe: How To Select For Each Row Different Column"