2

I have a data frame and I want to create a new column name "new" based on a condition on a different column "col". Create the new column name "new" and count it whenever it finds any value in "col".

  index      col        
    1     2.11.67       
    2       NaN        
    3       NaN        
    4     5.10.56      
    5       NaN        
    6     2.10.67      
    7       NaN        
    8     2.09.67      

should result in:-

 index      col        new
    1     2.11.67       1
    2       NaN        NaN
    3       NaN        NaN
    4     5.10.56       2
    5       NaN        NaN
    6     2.10.67       3
    7       NaN        NaN
    8     2.09.67       4
3
  • Google "pandas conditional running count" Commented Sep 23, 2021 at 18:25
  • Hi @Barmar I used below code but it throw error df.loc[df["col"].notna(),'new']+=1 Commented Sep 23, 2021 at 18:33
  • Edit the question with your attempt. Commented Sep 23, 2021 at 18:35

1 Answer 1

2

You can use a combination of notna, cumsum, and where:

mask = df['col'].notna()
df['new'] = mask.cumsum().where(mask)

output:

           col  new
index              
1      2.11.67  1.0
2          NaN  NaN
3          NaN  NaN
4      5.10.56  2.0
5          NaN  NaN
6      2.10.67  3.0
7          NaN  NaN
8      2.09.67  4.0
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.