0

I have a dataframe like the following (but longer) with some rows containing None values:

data = {'first Column':  ['she is', 'they are',NaN,'we are',NaN],
    'second Column ': ['my', 'her',NaN,'his',NaN],
    'third column': ['friend', 'brothers',NaN,'sisters',NaN]
    }

df = pd.DataFrame (data, columns = ['first Column','second Column','third column])

my_list= ['gold','silver','bronze']

I would like to replace every row in the 'third column' with a list if it does not contain none value, like this :

  desired output:
     first column   second column   third column
  0  she is          my             ['gold','silver','bronze']
  1  they are        her            ['gold','silver','bronze']
  2  NaN             NaN            NaN
  3  we are          his            ['gold','silver','bronze']
  4  NaN             NaN            NaN

I have tried np.where, but it does not select the desired rows

   np.where(df.loc[df['third column'] != 'NaN', [','.join(my_list)], df['third column']

1 Answer 1

2
df.loc[df['third column'].notna(),'third column']=[my_list]

Result:

  first Column second Column             third column
0       she is             my  [gold, silver, bronze]
1     they are            her  [gold, silver, bronze]
2          NaN            NaN                     NaN
3       we are            his  [gold, silver, bronze]
4          NaN            NaN                     NaN

PS: if you specifiy data as a dict with column names you don't need the columns argument in the dataframe constructor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.