如何在单个数据帧内进行vlookup?

王林
发布: 2024-02-09 11:21:16
转载
1111 人浏览过

如何在单个数据帧内进行vlookup?

问题内容

来自以下数据框(df):

|------------+--------------------+-------------|
| child_code | child_name         | parent_code |
|------------+--------------------+-------------|
|        900 | world              |           0 |
|        920 | south-eastern asia |         900 |
|        702 | singapore          |         920 |
|------------+--------------------+-------------|
登录后复制

我想生成这个数据框:

|------------+--------------------+-------------+--------------------|
| 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?
登录后复制


正确答案


您可以使用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
登录后复制

以上是如何在单个数据帧内进行vlookup?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板