首页 > 解决方案 > Pandas - 根据索引结果返回 pandas 中的相邻列

问题描述

我是熊猫新手,需要一些帮助。我有 2 个列表 A 和 B,A 是我正在组织的数据,B 是我用作参考的数据列表。

以下是列表 A 的示例。

     A
   Oringinal_String    Shortened_String    Price
1    BR3 6yh             BR3               56789
2    BL2 8hs             BL2               93882
3    AR3 9hs             AR3               67890
4    UB3 7hy             UB3               23453
5    BR3 7yh             BR3               76801

以下是列表 B 的示例

     B
     Oringinal_String    Shortened_String   Area
1    BR3 6yb             BR3                 MAN
2    BL2 2xs             BL2                 LON
3    XA2 1wl             XA2                 NEW
4    UB3 9xv             UB3                 LUT

我想找到在 B['shortened_string'] 中找到 A['shortened_string'] 并将 B['Area'] 附加到 A 的时间。

我想我已经设法索引以查找 A 何时出现在 B 中,但当我的索引为真时似乎无法退出 B['Area'],不确定这是否是正确的做法?

A.loc[A.index.isin(B['shortened_strin'])]

我希望走出去:

  A
     Oringinal_String    Shortened_String  Price    Area
1    BR3 6yh             BR3               56789    MAN
2    BL2 8hs             BL2               93882    LON
3    AR3 9hs             AR3               67890    
4    UB3 7hy             UB3               23453    LUT
5    BR3 7yh             BR3               76801    MAN

- 关键说明有重复的 A['shortened_strin']

标签: pythonpandas

解决方案


合并和一些清理

A.merge(B, on = 'Shortened_String', how = 'left', suffixes = ('', '_y')).drop('Oringinal_String_y',1).fillna('')


    Oringinal_String    Shortened_String    Price   Area
0   BR3 6yh             BR3                 56789   MAN
1   BL2 8hs             BL2                 93882   LON
2   AR3 9hs             AR3                 67890   
3   UB3 7hy             UB3                 23453   LUT
4   BR3 7yh             BR3                 76801   MAN

推荐阅读