Search code examples
python-3.xpandasif-statementconditional-statementscopy-paste

Copy and Paste Values Based on a Condition in Python


I am trying to populate column 'C' with values from column 'A' based on conditions in column 'B'. Example: If column 'B' equals 'nan', then row under column 'C' equals the row in column 'A'. If column 'B' does NOT equal 'nan', then leave column 'C' as is (ie 'nan'). Next, the values in column 'A' to be removed (only the values that were copied from column A to C).

Original Dataset:

index   A   B    C
0       6   nan  nan
1       6   nan  nan
2       9   3    nan
3       9   3    nan
4       2   8    nan
5       2   8    nan
6       3   4    nan
7       3   nan  nan
8       4   nan  nan

Output:

index   A   B    C
0       nan nan  6
1       nan nan  6
2       9   3    nan
3       9   3    nan
4       2   8    nan
5       2   8    nan
6       3   4    nan
7       nan nan  3
8       nan nan  4

Below is what I have tried so far, but its not working.

def impute_unit(cols):
    Legal_Block = cols[0]
    Legal_Lot = cols[1]
    Legal_Unit = cols[2]

    if pd.isnull(Legal_Lot):
       return 3
    else:
       return Legal_Unit

bk_Final_tax['Legal_Unit'] = bk_Final_tax[['Legal_Block', 'Legal_Lot', 
                          'Legal_Unit']].apply(impute_unit, axis = 1)

Solution

  • Seems like you need

    df['C'] = np.where(df.B.isna(), df.A, df.C)
    df['A'] = np.where(df.B.isna(), np.nan, df.A)
    

    A different, maybe fancy way to do it would be to swap A and C values only when B is np.nan

    m = df.B.isna()
    df.loc[m, ['A', 'C']] = df.loc[m, ['C', 'A']].values
    

    In other words, change

    bk_Final_tax['Legal_Unit'] = bk_Final_tax[['Legal_Block', 'Legal_Lot', 
                          'Legal_Unit']].apply(impute_unit, axis = 1)
    

    for

    bk_Final_tax['Legal_Unit'] = np.where(df.Legal_Lot.isna(), df.Legal_Block, df.Legal_Unit)
    bk_Final_tax['Legal_Block'] = np.where(df.Legal_Lot.isna(), np.nan, df.Legal_Block)