簡體   English   中英

Pandas DF 使用字典映射將數組中的值替換為列

[英]Pandas DF replace value in array with column using dictionary mapping

我有一個包含值數組的列的 DF,如下所示

姓名 網址
鮑勃 [https://1, https:/2]
瑪麗 [https://1,https:/3]

我想將“urls”列中數組中的值 map 到字典中,並將值替換為字典中的值。 下面的示例字典

mapping_dictionary = {'https:/1': 'google',
 'https:/2': 'yahoo',
 'https:/3': 'bing'}

所以最終結果看起來像這樣:

姓名 網址
鮑勃 [谷歌,雅虎]
瑪麗 [谷歌,必應]

是否可以使用 pandas.replace 或 pandas 映射來做到這一點?

提前致謝

您可以map explode mapping_dictionary”,按索引聚合到列表:

df['urls'] = df['urls'].explode().map(mapping_dictionary).groupby(level=0).agg(list)

Output:

   name             urls
0   bob  [google, yahoo]
1  mary   [google, bing]

讓我們試試

df['value' = df.urls.map(lambda x : [*map(mapping_dictionary.get, x)])
0    [google, yahoo]
1     [google, bing]
Name: urls, dtype: object

您可以使用applylambda更改網址,如下所示:

import pandas as pd

df = pd.DataFrame({
    'name': ['bob', 'mary'],
    'urls': [['https:/1', 'https:/2'], ['https:/1', 'https:/3']]
})

m_dict = {
    'https:/1': 'google',
    'https:/2': 'yahoo',
    'https:/3': 'bing'
}


df['urls'] = df['urls'].apply(lambda urls: [m_dict[url] for url in urls])

print(df)
#   name             urls
#0   bob  [google, yahoo]
#1  mary   [google, bing]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM