[英]Replacing a string value in one column based upon a list of other values in another column
I am cleaning a dataset and I need to replace the string in column A with "foo" if column B contains one of the strings from a list of options.我正在清理数据集,如果 B 列包含选项列表中的字符串之一,我需要将 A 列中的字符串替换为“foo”。
I have a list of values contained in column B that I want to use to indicate that I need to replace column A我有一个包含在 B 列中的值列表,我想用它来指示我需要替换 A 列
A B
foo apple
foo banana
bar cherry
foo orange
bar melon
bar papaya
I have multiple values that could trigger a replacement.我有多个可以触发替换的值。
list = ['papaya', 'avocado', 'cherry', 'mango']
using that list to inform the replacement I want to change the value in column A to foo if column B contains one of the values in the list.使用该列表通知替换项如果 B 列包含列表中的值之一,我想将 A 列中的值更改为 foo。 The results in this example would look like this.此示例中的结果如下所示。
A B
foo apple
foo banana
foo cherry
foo orange
bar melon
Any advice helps, thanks.任何建议都有帮助,谢谢。
Do:做:
lst = ['papaya', 'avocado', 'cherry', 'mango']
df.loc[df['B'].isin(lst), 'A'] = 'foo'
print(df)
Output Output
A B
0 foo apple
1 foo banana
2 foo cherry
3 foo orange
4 bar melon
5 foo papaya
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.