簡體   English   中英

pandas:根據列表和另一列條件替換逗號分隔列中的相應值

[英]pandas: replace corresponding values in a comma separated column based on a list and another column conditions

我有一個數據框和一個列表,如下所示:

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']

我想用 Names 列中的相應值替換 IDs 列中的逗號分隔值,以防它們出現在 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]))

並替換 IDs 列中的值,我嘗試了以下操作,但我不確定如何指示僅應更改相應的值,

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)

您可以split / explode ,然后從列表中替換您的值,然后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

暫無
暫無

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

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