How to vlookup within a single dataframe?

王林
Release: 2024-02-09 11:21:16
forward
1080 people have browsed it

How to vlookup within a single dataframe?

Question content

comes from the following data frame (df):

|------------+--------------------+-------------|
| child_code | child_name         | parent_code |
|------------+--------------------+-------------|
|        900 | world              |           0 |
|        920 | south-eastern asia |         900 |
|        702 | singapore          |         920 |
|------------+--------------------+-------------|
Copy after login

I want to generate this data frame:

|------------+--------------------+-------------+--------------------|
| child_code | child_name         | parent_code | parent_name        |
|------------+--------------------+-------------+--------------------|
|        900 | World              |           0 |                    |
|        920 | South-Eastern Asia |         900 | World              |
|        702 | Singapore          |         920 | South-Eastern Asia |
|------------+--------------------+-------------+--------------------|```
How could I make the equivalent of an MS Excel `vlookup` to produce the `parent_name` column?
Copy after login


Correct answer


You can use series.map:

import pandas as pd
import numpy as np

data = {'child_name': {0: 'World', 1: 'South-Eastern Asia', 2: 'Singapore'}, 
        'child_code': {0: 900, 1: 920, 2: 702}, 
        'parent_code': {0: 0, 1: 900, 2: 920}}
df = pd.DataFrame(data)

df['parent_name'] = df['parent_code'].map(df.set_index('child_code')['child_name'])

df

           child_name  child_code  parent_code         parent_name
0               World         900            0                 NaN
1  South-Eastern Asia         920          900               World
2           Singapore         702          920  South-Eastern Asia
Copy after login

The above is the detailed content of How to vlookup within a single dataframe?. 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!