How to add a value to a new column by referencing the values in a column

Viewed 58

I have a dataframe like this:

id  reason  x1    x2   x3   x4   x5 
 1  x1      100   15   10   20   25
 2  x1      15    16   14   10   10
 3  x4      10    50   40   30   25
 4  x3      12    15   60   5    1
 5  x1      80    15   10   20   25
 6  x1      15    19   84   10   10
 7  x4      90    40   90   30   25
 8  x4      12    85   60   50   10

The xy column must be filled with the value of the column names in the reason column. Let's look at the first row. The reason column shows our value x1. So our value in column xy, will be the value of x1 column in the first row. Like this:

id  reason  x1    x2   x3   x4   x5   xy
 1  x1      100   15   10   20   25   100
 2  x1      15    16   14   10   10   15
 3  x4      10    50   40   30   25   30
 4  x3      12    15   60   5    1    60
 5  x1      80    15   10   20   25   80
 6  x1      15    19   84   10   10   15
 7  x4      90    40   90   30   25   30
 8  x4      12    85   60   50   10   50

Is there a way to do this?

3 Answers
df["xy"] = df.apply(lambda x: x[x["reason"]], axis=1)
print(df)

Prints:

   id reason   x1  x2  x3  x4  x5   xy
0   1     x1  100  15  10  20  25  100
1   2     x1   15  16  14  10  10   15
2   3     x4   10  50  40  30  25   30
3   4     x3   12  15  60   5   1   60
4   5     x1   80  15  10  20  25   80
5   6     x1   15  19  84  10  10   15
6   7     x4   90  40  90  30  25   30
7   8     x4   12  85  60  50  10   50

You should just be able to add the new column like this:

xy = ['x1', 'x2', 'x3', 'x4']
df['xy'] = xy

With df being the name of your dataframe. But your example of what that column should contain is very unclear. Also post the code you have tried.

You can access columns and rows in the dataframe very easily. https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html I assume you are using pandas.

Let us try

df['new'] = df.values[df.index,df.columns.get_indexer(df.reason)]
df
   id reason   x1  x2  x3  x4  x5  new
0   1     x1  100  15  10  20  25  100
1   2     x1   15  16  14  10  10   15
2   3     x4   10  50  40  30  25   30
3   4     x3   12  15  60   5   1   60
4   5     x1   80  15  10  20  25   80
5   6     x1   15  19  84  10  10   15
6   7     x4   90  40  90  30  25   30
7   8     x4   12  85  60  50  10   50
Related