RE:Stacked

We are taking the classic Stack Overflow questions and answers and providing a more human readable…

Member-only story

Generate Column Name Lookup in Python

Kyle Pastor
RE:Stacked
Published in
2 min readJul 14, 2023

--

Photo by Alex Chumak on Unsplash

Disclaimer: Solution by ChatGPT and validated by human.

Question

Say I have

df = pl.DataFrame({
'a': [1, 2, 1],
'b': [2, 1, 2],
'c': [3, 3, 2],
'column': ['a', 'c', 'b'],
})
shape: (3, 4)
┌─────┬─────┬─────┬────────┐
│ a ┆ b ┆ c ┆ column │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╪════════╡
│ 1 ┆ 2 ┆ 3 ┆ a │
│ 2 ┆ 1 ┆ 3 ┆ c │
│ 1 ┆ 2 ┆ 2 ┆ b │
└─────┴─────┴─────┴────────┘

I want add a column which, for each row, take the value in the row corresponding to the column in column.

Expected output:

shape: (3, 5)
┌─────┬─────┬─────┬────────┬────────┐
│ a ┆ b ┆ c ┆ column ┆ lookup │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ str ┆ i64 │
╞═════╪═════╪═════╪════════╪════════╡
│ 1 ┆ 2 ┆ 3 ┆ a ┆ 1 │
│ 2 ┆ 1 ┆ 3 ┆ c ┆ 3 │
│ 1 ┆ 2 ┆ 2 ┆ b ┆ 2 │
└─────┴─────┴─────┴────────┴────────┘

Solution

import pandas as pd

df = pd.DataFrame({
'a': [1, 2, 1],
'b': [2, 1, 2],
'c': [3, 3, 2],
'column': ['a', 'c', 'b'],
})

df['lookup'] = df.apply(lambda row: row[row['column']], axis=1)
print(df)

Reference

--

--

RE:Stacked
RE:Stacked

Published in RE:Stacked

We are taking the classic Stack Overflow questions and answers and providing a more human readable and well commented output with the help of ChatGPT.

Kyle Pastor
Kyle Pastor

Written by Kyle Pastor

Analytics | Full Stack | Data Science | MS Physics + MS Quant Finance → http://kapastor.github.io/

No responses yet