简体   繁体   中英

Fill Dataframe column based on values

I have a dataframe with several columns, each column has binary values. for each columns I have a numpy array with some values with same length of the column.

I need to fill the column with the numpy array but with one condition: fill only if the value in the dataframe column is 0, if it's one don't fill from the numpy array.

Using for loops I would get something like this:

 for col in df.columns:
  for i in df[col]:
    if df.loc[i,col] == 0:
      df.at[i,col] = arr[i,col]
    else:
      continue

However this is slow and my dataframe is a bit big (10k row * 180 columns), I'm looking if there's any elegant pythonic way to do this

You can try

df=df.mask(df==0,arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM