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

WBOY
Release: 2024-02-14 10:03:04
forward
685 people have browsed it

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)
Copy after login

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
Copy after login

If the column's type is integer, remove the inner str():

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!