mardi 5 novembre 2019

Several Layers of If Statements with String

I have a data frame

df = pd.DataFrame([[3,2,1,5,'Stay',2],[4,5,6,10,'Leave',10],
                   [10,20,30,40,'Stay',11],[12,2,3,3,'Leave',15],
                   [31,23,31,45,'Stay',25],[12,21,17,6,'Stay',15],
                   [15,17,18,12,'Leave',10],[3,2,1,5,'Stay',3],
                   [12,2,3,3,'Leave',12]], columns = ['A','B','C','D','Status','E'])


    A   B   C   D Status   E
0   3   2   1   5   Stay   2
1   4   5   6  10  Leave  10
2  10  20  30  40   Stay  11
3  12   2   3   3  Leave  15
4  31  23  31  45   Stay  25
5  12  21  17   6   Stay  15
6  15  17  18  12  Leave  10
7   3   2   1   5   Stay   3
8  12   2   3   3  Leave  12

I want to run a condition where if Status is Stay and if column E is smaller than column A, then: change the data where data in column D is replaced with data column C, data in column C is replaced with data from column B and data in column B is replaced with data from column A and data in column A is replaced with data from column E. If Status is Leave and if column E is larger than column A, then: change the data where data in column D is replaced with data column C, data in column C is replaced with data from column B and data in column B is replaced with data from column A and data in column A is replaced with data from column E.

So the result is:

    A   B   C   D Status   E
0   2   3   2   1   Stay   2
1  10   4   5   6  Leave  10
2  10  20  30  40   Stay  11
3  15  12   2   3  Leave  15
4  25  31  23  31   Stay  25
5  12  21  17   6   Stay  15
6  15  17  18  12  Leave  10
7   3   2   1   5   Stay   3
8  12   2   3   3  Leave  12

My attempt:

if df['Status'] == 'Stay':
    if df['E'] < df['A']:
        df['D'] = df['C']
        df['C'] = df['B']
        df['B'] = df['A']
        df['A'] = df['E']
elif df['Status'] == 'Leave':
        if df['E'] > df['A']:
        df['D'] = df['C']
        df['C'] = df['B']
        df['B'] = df['A']
        df['A'] = df['E']

This runs into several problems including problem with string. Your help is kindly appreciated.

Aucun commentaire:

Enregistrer un commentaire