Home > other >  Create a new column using a condition from other two columns in a dataframe
Create a new column using a condition from other two columns in a dataframe

Time:08-15

I'm trying to create a column as I detailed in the next lines of code where if there is a zero value in one of the rows of the dataframe create a 'Sin Valor' value in the row of the new column of this dataframe.

import pandas as pd

data = pd.DataFrame({
        'Qu1' : [12,34,0,45,0],
        'Qu2' : ['A1','A2',"B0",'C2','B0'],
        'Control' : ['A1', 'A2','Sin Valor/ -'   "B0" ,'C2','Sin Valor/ -'  "B0"]})

In Excel, what I am trying to do should be something like this picture attached.

enter image description here

I was trying to create a function to do that and applying via lambda function but this isn´t working.

def fill_df(x):
    if data["Qu1"] == 0:
        return x.zfill('Sin Valor/ -')
    else: 
        return ' ' 
data['Control'] = data.apply(fill_df)

Is it possible to do that ? Every help is welcome. Thanks.

CodePudding user response:

use np.where to accomplish it

df['ctrl'] = np.where(df['Qu1'] == 0,
                     'Sin Valor/-' df['Qu2'],
                     df['Qu2'])
df

I introduced 'ctrl' column, that meets your requirement and matches 'control' (desired) column

    Qu1     Qu2     Control         ctrl
0    12     A1      A1              A1
1    34     A2      A2              A2
2     0     B0      Sin Valor/ -B0  Sin Valor/-B0
3    45     C2      C2              C2
4     0     B0      Sin Valor/ -B0  Sin Valor/-B0

CodePudding user response:

mask = df['Qu1'] == 0
df.loc[mask, 'Control'] = 'Sin Valor/ -'   df['Qu2'][mask]
  • Related