How to update a pandas column with a string constant and number(count)

401 Views Asked by At

I have 2 panda columns that looks like so:

Request Number         Cost Center
       1                  111
       2                  133 
       3                  156 
      NaN                 235 
      NaN                 111
      NaN                 123

For the NaN (null values), how can I get the Pandas dataframe to look like so:

Request Number         Cost Center
       1                  111
       2                  133 
       3                  156 
    Unknown1              235 
    Uknnown2              111
    Unknown3              123

Where all null values will take the form of the string constant of unknown with the count in order?

1

There are 1 best solutions below

0
On

You can modify the null values in Request Number using .loc, and concatenating the string "Unknown" to the cumsum of null values, cast as string:

df.loc[df['Request Number'].isnull(), 'Request Number'] = 'Unknown' + df['Request Number'].isnull().cumsum().astype(str)

>>> df
  Request Number  Cost Center
0              1          111
1              2          133
2              3          156
3       Unknown1          235
4       Unknown2          111
5       Unknown3          123