首页 > 解决方案 > 如何像在 Pandas 中一样进行索引和匹配

问题描述

我正在尝试在 Pandas 中使用类似索引和匹配的功能。我是新来的。我想做的是

  1. 索引字符串或多个字符串并更改相应的价格

  2. 索引字符串,不考虑大小写字母(许多水果的名称全大写,一个大写,其余小写,或全小写)

    fruits                  price
    apple from us           10
    Apple from US           11
    Mango from Canada       15
    Orange from Mexico      16
    Orange from Costa       15
    Orange from Brazil      19
    Pear from Guatemala     32
    Melon from Guatemala    4
    orange from Honduras    5
    

我试过 df.loc[df['fruits'].str.contains('apple'), 'Target Price'] = 275 但我得到了

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       275
    Orange from Mexico      275
    Orange from Costa       275
    Orange from Brazil      275
    Pear from Guatemala     275
    Melon from Guatemala    275
    Orange from Honduras    275

但我想要的是

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      16
    Orange from Costa       15
    Orange from Brazil      19
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5

此外,上面的行不允许我有多个条件,比如包含“橙色”但不是来自洪都拉斯。有没有办法只排除某些字符串是否也在其中,以便我可以将 Orange 的价格设置为 222,但来自洪都拉斯的 Orange 保持原样。

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      222
    Orange from Costa       222
    Orange from Brazil      222
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5

标签: pythonpandas

解决方案


你可以转换成小写

>>> d_f.loc[d_f['Fruits'].str.lower().str.contains('apple'), 'Price'] = 275
>>> d_f
                 Fruits Price
0         apple from us   275
1         Apple from US   275
2     Mango from Canada    15
3    Orange from Mexico    16
4     Orange from Costa    15
5    Orange from Brazil    19
6   Pear from Guatemala    32
7  Melon from Guatemala     4
8  orange from Honduras     5

推荐阅读