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

bak*_*net 4 python dictionary replace dataframe pandas

这是一个示例,其中当行是字典键时分配列: /sf/answers/1417569751/

我正在寻找的是当行包含字典键时分配列的情况。

例如(基于上面的例子):

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
Run Code Online (Sandbox Code Playgroud)

Ch3*_*teR 5

您可以将DataFrame.replace参数regex设置为 True 并传递映射字典。

df.replace(dictionary, regex=True)

#   col2
# 0    5
# 1  abc
# 2    8
Run Code Online (Sandbox Code Playgroud)

的这种用法df.replace鲜为人知。你可以在这里读更多关于它的内容。