vendredi 24 avril 2020

Create a multiple if statement and a function to replace values in columns

I am working with a large dataset, but in order to simplify, I will use a simpler example (whose some rows have been deleted to clean the dataset) in order to illustrate the problem. Imagine I have this dataset:

    Code_0  Code_1  Code_3  Code_4  Code_5 Code_6 Code_7
3     1        1       3       0        0    1      1 
9     0        0       0       0        0    0      1
10    4        2       3       1        1    0      0
15    0        3       0       5        1    1      1 

So, what I want to do in every row is, If Code_5 is equal to one and code_0 is bigger than 0, then, to code_0 will be added one. On the other hand, if code_6 == 1,and code_1 is bigger than 0, then to code_1 will be added one. Finally, if code_7 == 1 and code_3 is bigger than 0, than to code_3 will be added 1. So I want to have this:

    Code_0  Code_1  Code_3  Code_4  Code_5 Code_6 Code_7
3     1        2       4       0        0    1      1 
9     0        0       0       0        0    0      1
10    5        2       3       1        1    0      0
15    0        4       0       5        1    1      1 

I did this code but it is not working. Anyway I think that there is maybe a better option.

def add_one(x):
    if x == df_data['Code_5']:
        if x == 1 and df_data['Code_0'] > 0:
            df_data['Code_0'] = df_data['Code_0'] + 1
    if x == df_data['Code_6']:
        if x == 1 and df_data['Code_1'] > 0:
            df_data['Code_1'] = df_data['Code_1'] + 1  
    if x == df_data['Code_7']:
        if x == 1 and df_data['Code_2'] > 0:
            df_data['Code_2'] = df_data['Code_2'] + 1

df_data['Code_0'] = df_data['Code_5'].apply(add_one)
df_data['Code_1'] = df_data['Code_6'].apply(add_one)
df_data['Code_2'] = df_data['Code_7'].apply(add_one)

Anyone can help me, please?

Aucun commentaire:

Enregistrer un commentaire