Home  >  Article  >  Backend Development  >  Using a string in one column of a dataframe to reference a value in another column

Using a string in one column of a dataframe to reference a value in another column

WBOY
WBOYforward
2024-02-14 10:03:04686browse

Using a string in one column of a dataframe to reference a value in another column

Question content

Trying to use a value from a column in a dataframe (placeholder) to reference a specific column in the same dataframe... Wondering if this is possible. Examples of input and output below:

enter:

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 finals 标题> 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 greatly appreciated!


Correct answer


Attempt:

df["final"] = df.apply(lambda x: str(x[str(x["placeholder"])]) + "_id", axis=1)
print(df)

Print:

       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 column's type is integer, remove the inner str():

df["final"] = df.apply(lambda x: str(x[x["placeholder"]]) + "_ID", axis=1)

The above is the detailed content of Using a string in one column of a dataframe to reference a value in another column. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete