python - 如何像在 Pandas 中一样进行索引和匹配
问题描述
我正在尝试在 Pandas 中使用类似索引和匹配的功能。我是新来的。我想做的是
索引字符串或多个字符串并更改相应的价格
索引字符串,不考虑大小写字母(许多水果的名称全大写,一个大写,其余小写,或全小写)
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
解决方案
你可以转换成小写
>>> 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
推荐阅读
- botframework - 在 Skype For Business 上使用 Skype 机器人
- spring-boot - 无法在 Spring Boot 应用程序中使用执行器
- monaco-editor - Monaco Editor registerCompletionItemProvider 移除默认的局部变量完成
- python - 是否可以在 python 中更改 PixelAccess 的大小?
- android - txt文件中的可点击单词
- javascript - 我正在尝试使用此代码验证我的购物清单,“...”传播但得到“牛奶”的返回值,并且只是第一个值
- haskell - 定义数据类型时无法匹配预期类型
- c# - 如何使用 C#/Command 调用板载声音
- logging - Hybris 默认在哪里存储 Cronjob 日志?
- vb.net - 从 vb.net 中的数据网格视图更新数据库