如何像熊猫一样进行索引和匹配

时间:2019-05-29 18:50:55

标签: python 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”,但不是来自洪都拉斯。有没有一种方法可以只排除某些字符串,以便我可以将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

1 个答案:

答案 0 :(得分:0)

您可以转换为小写

>>> 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