[英]Replace Pandas DataFrame column values based on containing dictionary keys
Here is an example, where column is assigned when the row is<\/strong> a dictionary key: https:\/\/stackoverflow.com\/a\/20250996\/12603542<\/a>这是一个示例,当行是<\/strong>字典键时分配列:
https<\/a> :\/\/stackoverflow.com\/a\/20250996\/12603542
For example (based on example above):例如(基于上面的示例):
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
You could use DataFrame.replace<\/code><\/a> with
regex<\/code> parameter set to True and pass the mapping dictionary.
您可以使用
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.