Search code examples
pythonpandasdataframeassign

Populate Pandas DataFrame using a dictionary based on a condition


I have a DataFrame

>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]})
    A   B   C   D
0   a   1       
1   b   2       
2   b   3       
3   b   4       

I also have a dictionary, where b in input_b signifies that I'm only modifying rows where row.A = b.

>> input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']}

How do I populate the DataFrame with values from the dictionary to get

    A   B   C       D
0   a   1       
1   b   2   Moon    Elephant
2   b   3       
3   b   4   Sun     Mouse

Solution

  • Using apply

    test['C'] = test['B'].map(input_b).apply(lambda x: x[0] if type(x)==list else x)
    test['D'] = test['B'].map(input_b).apply(lambda x: x[1] if type(x)==list else x)
    

    yields

       A  B     C         D
    0  a  1   NaN       NaN
    1  b  2  Moon  Elephant
    2  b  3   NaN       NaN
    3  b  4   Sun     Mouse