简体   繁体   English

根据包含的字典键替换 Pandas DataFrame 列值

[英]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

What I am looking for is case, where column is assigned when the row contains<\/strong> a dictionary key.我正在寻找的是当行包含<\/strong>字典键时分配列的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM