Home > Blockchain >  Pandas create a new column based on string-matching values from another column
Pandas create a new column based on string-matching values from another column

Time:11-05

Is there any way to create a new column based on string-matching values from another column without duplicating the column and replacing the values?

So far this is one solution that I am using:


df = pd.DataFrame({
        "Task": ["T1", "T1", "T2", "T3","T3"],
        "Complexity": [1, 2, 3, 2, 1],
        "Status": ["OpenA", "ClosedB", "ClosedC", "OpenC", "OpenA"]})

df['Statno']=df['Status']
df=df.replace({'Statno':{'(?i).*Open.*': '1', '(?i).*Close.*' : '0' }}, regex=True)
df

CodePudding user response:

like that?

import pandas as pd

df = pd.DataFrame({
        "Task": ["T1", "T1", "T2", "T3","T3"],
        "Complexity": [1, 2, 3, 2, 1],
        "Status": ["OpenA", "ClosedB", "ClosedC", "OpenC", "OpenA"]})

df['Statno']=df['Status'].replace({'(?i).*Open.*': '1', '(?i).*Close.*' : '0' }, regex=True)
df
  • Related