python - pandas:根据列表和另一列条件替换逗号分隔列中的相应值

标签 python pandas list apply str-replace

我有一个数据框和一个列表,如下所示:

import pandas as pd
import numpy as np

df = pd.DataFrame({'IDs':['d,f,o','d,f','d,f,o','d,f','d,f'],
                'Names':['APPLE ABCD ONE','date ABCD','NO foo YES','ORANGE AVAILABLE','TEA AVAILABLE']})

my_list = ['APPLE', 'ORANGE', 'LEMONS', 'STRAWBERRY', 'BLUEBERRY']

我想将 ID 列中的逗号分隔值替换为“名称”列中的相应值,以防它们出现在 my_list 中。

desired output:
df.IDs => ['APPLE,f,o', 'd,f', 'd,f,o', 'ORANGE,f', 'd,f']

查明该行是否包含我尝试过的列表中的值:

df['Names'].apply(lambda x: any([k in x for k in my_list]))

为了替换 ID 列中的值,我尝试了以下操作,但我不确定如何指示仅应更改相应的值,

df.IDs.apply(lambda i: i if i in my_list else 'don't know what to do here')

我想我可以使用 np.where() 根据条件执行整个替换

np.where(df['Names'].apply(lambda x: any([k in x for k in my_list])) == True, df.IDs.apply(lambda i: i if i in my_list else 'don't know what to do here'), df.IDs)

最佳答案

您可以分割/爆炸,然后替换列表中的值,然后agg恢复到原始形状:

(df.assign(IDs=df['IDs'].str.split(','),     # strings to lists
           Names=df['Names'].str.split(' ')
          )
   .apply(pd.Series.explode)                 # lists to rows
    # map the Names in place of Ids is in my_list
   .assign(IDs=lambda d: d['IDs'].mask(d['Names'].isin(my_list), d['Names']))
    # reshape back to original by joining
   .groupby(level=0).agg({'IDs': ','.join, 'Names': ' '.join})
)

输出:

         IDs             Names
0  APPLE,f,o    APPLE ABCD ONE
1        d,f         date ABCD
2      d,f,o        NO foo YES
3   ORANGE,f  ORANGE AVAILABLE
4        d,f     TEA AVAILABLE

关于python - pandas:根据列表和另一列条件替换逗号分隔列中的相应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69755132/

相关文章:

list - 列表中最长的单词

python:使用remove()按值从列表中删除元素

python - 当查询以注释开始时,python 的 sqlite3 中的隐式提交

python - 单元测试应该如何与外部资源一起工作?什么是正确的做法?

python - 升级 Ubuntu : python3 install is corrupted

python - Pandas idxmax() 不适用于按包含 NaN 的时间段分组的系列

python - 从行中提取每日值并使用日期创建新行

python - 如何使用 pandas 有效地为序列中缺少的数据点添加行?

python - 如果匹配则返回匹配

jQuery - 操作可排序列表中删除的元素