简体   繁体   English

更新与正则表达式条件匹配的数据帧值并保持剩余值不变

[英]Update dataframe values that match a regex condition and keep remaining values intact

The following is an excerpt from my dataframe:以下是我的数据框的摘录:

In[1]: df
Out[1]:
     LongName   BigDog   
1     Big Dog        1  
2     Mastiff        0    
3     Big Dog        1   
4         Cat        0   

I want to use regex to update BigDog values to 1 if LongName is a mastiff.如果 LongName 是獒犬,我想使用正则表达式将 BigDog 值更新为 1。 I need other values to stay the same.我需要其他价值观保持不变。 I tried this, and although it assigns 1 to mastiffs, it nulls all other values instead of keeping them intact.我试过了,虽然它为獒犬分配了 1,但它会将所有其他值归零,而不是保持它们完好无损。

def BigDog(longname): 
    if re.search('(?i)mastiff', longname):
        return '1'

df['BigDog'] = df['LongName'].apply(BigDog) 

I'm not sure what to do, could anybody please help?我不知道该怎么办,有人可以帮忙吗?

You don't need a loop or apply, use str.match with DataFrame.loc :您不需要循环或应用,将str.matchDataFrame.loc str.match使用:

df.loc[df['LongName'].str.match('(?i)mastiff'), 'BigDog'] = 1

  LongName  BigDog
1  Big Dog       1
2  Mastiff       1
3  Big Dog       1
4      Cat       0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据正则表达式匹配替换数据框中的字符串值 - Replace string values in a dataframe based on regex match 删除满足列值条件的熊猫数据框的初始行,同时保持列中的序列值不变 - Delete initial rows of a pandas dataframe that satisfy column value condition while keeping the sequence values in a column intact pandas 在列值匹配时使用来自另一个数据帧的值更新数据帧 - pandas update a dataframe with values from another dataframe on the match of column values 使用 if else 条件更新熊猫数据框值? - Update pandas dataframe values with if else condition? 根据字典和条件更新 dataframe 中的值 - Update values in dataframe based on dictionary and condition 通过正则表达式和匹配条件过滤 DataFrame - Filter DataFrame by regex and match condition 如何根据条件从另一个 Dataframe 更新 Dataframe 值 - How to update a Dataframe values from an another Dataframe based on condition 如何在条件变化的函数中匹配DataFrame列上的值? - How to match values on DataFrame column in function of a changing condition? 查找具有与 dataframe 中的条件匹配的近似值的所有行 - Finding all the rows with the approximate values that match a condition in a dataframe 如何在与正则表达式匹配的 Pandas DataFrame 中找到实际的唯一值 - How to find actual unique values in pandas DataFrame that match a regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM