Alexandr Kapshuk
Alexandr Kapshuk

Reputation: 1471

Python Pandas: Call column name from column assignment

I have the following dataframe:

number_1 number_2 number_3 ... number_100 index
1        2        2000         8          3
201      10       21           2          1
...

I want to create a new column, which is equal to the number_index like this:

number_1 number_2 number_3 ... number_100 index number_index
1        2        2000         8          3     2000
201      10       21           2          1     201
...

Is something like table['number_index'] = table['number_' + str(table['index'])] possible?

Upvotes: 1

Views: 512

Answers (3)

Luis G. Montero
Luis G. Montero

Reputation: 1

I don´t really understand your question. If you are looking to put a variable in a name I would suggest the exec command.

exec("table['number_index'] = " + f'''table['number_' + {str(table['index'])}]'''

Thus you can execute a string command. With f'''{var_name}''' you can combine strings and variables.

Upvotes: 0

Naveen
Naveen

Reputation: 1210

You are almost there. Since you have to do for every row, you can use lambda function to get this done.

table['number_index'] = table.apply(lambda x: x["number_" + str(x['index'])], axis = 1)

Upvotes: 1

BENY
BENY

Reputation: 323226

Using lookup after str split of the columns name

df1=df.copy()
df1.columns=df1.columns.str.split('_').str[-1]
df['Newval']=df1.lookup(df.index,df['index'].astype(str))
df
Out[34]: 
   number_1  number_2  number_3  number_100  index  Newval
0         1         2      2000           8      3    2000
1       201        10        21           2      1     201

Upvotes: 1

Related Questions