Home > Software design >  Assign empty value based on a zip list python
Assign empty value based on a zip list python

Time:04-29

I have a df like this:

df=pd.DataFrame({'A':[np.nan, np.nan, 'w', np.nan, 'y', np.nan],
                 'B': [np.nan, 'G',   'G', np.nan, 'R', 'R'   ]})
# And I zipped the unique values of the two groups together

univalue=zip(df.A.dropna().unique().tolist(), df.B.dropna().unique().tolist())

I want to assign values to column A if values in B are not nan, column A has the coordinate value in the zip list. So that the df will be like below. Is there any way to do that?

> df
A     B
nan   nan
'w'   'G'
'w'   'G'
nan   nan
'y'   'R'
'y'   'R'

CodePudding user response:

If I understand you correctly, you can create a mapping dictionary and then use .map to assign to column "A":

univalue = dict(zip(df.B.dropna().unique(), df.A.dropna().unique()))

df["A"] = df["B"].map(univalue)
print(df)

Prints:

     A    B
0  NaN  NaN
1    w    G
2    w    G
3  NaN  NaN
4    y    R
5    y    R
  • Related