Home > Net >  python creating new column with results in dataframe
python creating new column with results in dataframe

Time:12-24

I have a dataframe with float values. I want to create a new column that is the ratio of columns A and B of my dataframe.

what am i doing wrong ?

df['Result']= np.nan if (np.isnan(df['A']) or np.isnan(df['B'])) else df['B']/df['A'] 

CodePudding user response:

You can try this way with np.where,

df['Result'] = np.where((np.isnan(df['A']) | np.isnan(df['B'])), np.nan, df['B'] / df['A'])

Issue with your approach:

The value np.nan is being assigned to the entire 'Result' column, regardless of whether the conditions specified in the if statement are met. The if statement is not being used to control which rows in the 'Result' column get assigned a value of np.nan and which rows get assigned a value of df['B']/df['A'].

To use the if statement to control the assignment of values to the 'Result' column, you would need to use a loop to iterate over the rows in the DataFrame and test the conditions for each row. Like-

for i, row in df.iterrows():
    if np.isnan(row['A']) or np.isnan(row['B']):
        df.loc[i, 'Result'] = np.nan
    else:
        df.loc[i, 'Result'] = row['B'] / row['A']

CodePudding user response:

hello you can also use np.select() : that very helpfull when you have alot of condition

#step1: creat list of condition 

condition= [ 
            df['A'].notnull()|df['B'].notnull(),
            df['A'].isnull()|df['B'].isnull()
            ]
#step2: creat list of values

values= [(df['B'] / df['A']),np.nan]
#then create clomun and put the value if condition is True

df['Result']=np.select(condition,values)
  • Related