Home > Net >  How to generate numbers and store in particular rows of a column in dataframe
How to generate numbers and store in particular rows of a column in dataframe

Time:11-02

I just need to generate the numbers and store in the column C in the blank spaces

Data

   A        B      C
12525    1FWE23   
14654    14654    
24798    24798    
38945    38945     
46456    46485     8
AD545    45346     9
A5D66    A5D66     10

Expected

   A        B      C
12525    1FWE23    0
14654    14654     1
24798    24798     2
38945    38945     3
46456    46485     8
AD545    45346     9
A5D66    A5D66     10

CodePudding user response:

First create mask for select rows and assign range with sum True values for lenght:

#C has empty strings
m = df.C.eq('')

#C has missing values
# m = df.C.isna()

df.loc[m, 'C'] = range(m.sum())
print (df)
       A       B   C
0  12525  1FWE23   0
1  14654   14654   1
2  24798   24798   2
3  38945   38945   3
4  46456   46485   8
5  AD545   45346   9
6  A5D66   A5D66  10

CodePudding user response:

Try this way using apply:

import pandas as pd
data = {
  "A": [12525, 14654, 24798, 24798, 13231],
  "B": [12525, 24798, 24798, 24798, 21231],
  "C": ['', '', 2, '', 4]
}
df = pd.DataFrame(data)
def null_check(row):
    if row['C'] != '':
        return row['C']
    return row.name
df['C'] = df.apply(null_check, axis=1)
print(df)

Output:

pandas

  • Related