[英]How to replace pandas dataframe column values based on dictionary key and values?
[英]Replace Pandas DataFrame column values based on containing dictionary keys
这是一个示例,当行是<\/strong>字典键时分配列: https<\/a> :\/\/stackoverflow.com\/a\/20250996\/12603542
我正在寻找的是当行包含<\/strong>字典键时分配列的情况。
例如(基于上面的示例):
import pandas as pd
df = pd.DataFrame({'col1': {0: 'aba', 1: 'abc', 2: 'abx'}})
#gives me a DataFrame
col1
0 aba #contains 'ba'
1 abc #will NOT be replaced
2 abx #contains 'bx'
dictionary = {'ba': 5, 'bx': 8}
#and I need to get:
col1
0 5
1 abc
2 8
您可以使用
DataFrame.replace<\/code><\/a>并将
regex<\/code>参数设置为 True 并传递映射字典。
df.replace(dictionary, regex=True)
# col2
# 0 5
# 1 abc
# 2 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.