2

I want to iterate and modify the values under a column 'B', which have repeated values.

So for example if my data frame is like

A   B    
1   null,null    
2   null    
3   null,null,null    
4   null,apples    
5   null,apples,null    
6   null,apples,apples

Now I want to modify this so that a new column C is created in the data frame, depending on the column values from B. It will do the following:

  1. Replace all the multiple "Nulls" with just a single "null" value
  2. If there is an occurrence of the word apples, then we store "apples" in the new column instead of null.

Desired output-

A   B                  C

1   null,null          null

2   null               null

3   null,null,null     null

4   null,apples         apples

5   null,apples,null    apples

6   null,apples,apples  apples
2
  • Do you have null string or None in your column? Commented Jun 13, 2019 at 13:37
  • "Null" is the string value Commented Jun 13, 2019 at 13:39

2 Answers 2

3

Try

df['C'] = (df.B.str.split(',',expand=True)  # split the string and put them as columns
            .replace('null',np.nan)         # replace all the null with nan values
            .bfill(axis=1)[0]               # fill the nan to the left and choose the first column
            .fillna('null')                 # replace the nan values with string 'null'
          )
Sign up to request clarification or add additional context in comments.

1 Comment

+1, but I would define / wrap it in a seperated function. Easier to understand, easier to test. The question has not much to do with data-frames. It is about a mapping which maps (from my understanding) strings like null,apples,null to apples. The data-frame is just to hold the originals and images.
2

Using get_dummies

s=df.B.str.get_dummies(',').drop('null',1)

df['New']=s.dot(s.columns).replace('','null')
df
Out[143]: 
   A                   B     New
0  1           null,null    null
1  2                null    null
2  3      null,null,null    null
3  4         null,apples  apples
4  5    null,apples,null  apples
5  6  null,apples,apples  apples

1 Comment

quite a clever answer

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.