簡體   English   中英

我想基於上一列添加一個新的 DataFrame 列,以便如果上一列元素與列表值匹配,則更改該值

[英]I want to add a new DataFrame column based on previous column such that if previous column element matches with list value, change the value

輸入 df

Index       col1
0     Img    
1     Fruit  
2     Img    
3     Ball    
4     Ball    
5     Fruit    
6     shirt    
7     Fruit 

將列表映射到輸入 df

list1 = ['Img_A_10', 'Fruit_A_100', 'Ball_B_120']

輸出 df

     col1      col22
0     Img    Img_A_10
1     Fruit  Fruit_A_100
2     Img    Img_A_10
3     Ball   Ball_B_120
4     Ball   Ball_B_120
5     Fruit  Fruit_A_100  
6     shirt  shirt         
7     Fruit  Fruit_A_100

嘗試這個,

df['col2'] = df.col1.map({k.split("_")[0]: k for k in list1}).fillna(df.col1)

或者

df['col2'] = df.col1.replace({k.split("_")[0]: k for k in list1})

df
Out[93]: 
    col1         col2
0    Img     Img_A_10
1  Fruit  Fruit_A_100
2    Img     Img_A_10
3   Ball   Ball_B_120
4   Ball   Ball_B_120
5  Fruit  Fruit_A_100
6  shirt        shirt
7  Fruit  Fruit_A_100

以防萬一拆分不匹配(例如: A_Fruit_100 ),您可以extract然后replace

s = pd.Series(list1)
d = dict(zip(s.str.extract('('+'|'.join(df['col1'])+')',expand=False),s))
df['col22'] = df['col1'].replace(d)

print(df)
        col1        col22
Index                    
0        Img     Img_A_10
1      Fruit  Fruit_A_100
2        Img     Img_A_10
3       Ball   Ball_B_120
4       Ball   Ball_B_120
5      Fruit  Fruit_A_100
6      shirt        shirt
7      Fruit  Fruit_A_100

暫無
暫無

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

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