trying to use values from a column in the dataframe (placeholder) to reference a specific column in the same dataframe... was wondering if this is even possible. Example input and output below:
Input:
ID | 1 | 2 | 3 | placeholder |
---|---|---|---|---|
9234 | 923 | 12 | 942 | 2 |
203841 | 1230 | 438 | 1029 | 1 |
94532 | 4380 | 312 | 349 | 3 |
Output:
ID | 1 | 2 | 3 | placeholder | final |
---|---|---|---|---|---|
9234 | 923 | 12 | 942 | 2 | 12_ID |
203841 | 1230 | 438 | 1029 | 1 | 1230_ID |
94532 | 4380 | 312 | 349 | 3 | 349_ID |
Any help would be much appreciated!
Try:
df["final"] = df.apply(lambda x: str(x[str(x["placeholder"])]) + "_ID", axis=1)
print(df)
Prints:
ID 1 2 3 placeholder final
0 9234 923 12 942 2 12_ID
1 203841 1230 438 1029 1 1230_ID
2 94532 4380 312 349 3 349_ID
If the columns are of type integer, remove the inner str()
:
df["final"] = df.apply(lambda x: str(x[x["placeholder"]]) + "_ID", axis=1)