user12367917
user12367917

Reputation:

Use column value to find colum name

I have a dataframe:

import pandas as pd 

data = {"name": ["a", "b", "c"], "1": [0.65, 0.001, None], "2": [0.02, 0.0011, 1.2], "3": [0.12, 0.231, 55.2], "index": [1, 2, 3]}

df = pd.DataFrame (data, columns = ['name', '1', '3', '2', "index"])

And if the "index" value for a row is the same as the column name then add the column names correpsonding value to a new dataframe. For example for the first row "a", the index is 1 which so then add the value for the "1" column 0.65 to a new dataframe.

I am struggling to explain this, but this is what I wish to end up with:

data2 = {"name": ["a", "b", "c"], "val": [0.65, 1.2, 0.231]}

df2 = pd.DataFrame (data2, columns = ['name', 'val'])

Upvotes: 0

Views: 36

Answers (1)

BENY
BENY

Reputation: 323326

Let us try lookup

df['val']=df.lookup(df.index,df['index'].astype(str))
df
Out[116]: 
  name      1       3       2  index      val
0    a  0.650   0.120  0.0200      1   0.6500
1    b  0.001   0.231  0.0011      2   0.0011
2    c    NaN  55.200  1.2000      3  55.2000

Upvotes: 1

Related Questions