Member-only story
Generate Column Name Lookup in Python
Asker: ignoring_gravity
Published in
2 min readJul 14, 2023
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)