Return Second Value of the Column IF the first column empty in Python Pandas

Viewed 548

I have this table in my Pandas Dataframe (Store_id and Sub_store)

           Store_id   Sub_store
1             26821           
2                       26821B
3             26823     26823AV
4                       26823B
5                      26824DCF

I would like to return the All_ID column by 1. Return the values of the stored_id column, IF empty return Sub_store column and strip de Strings Characters.

How I Can return the result "ALL ID" in my python Pandas Dataframe?

Expected Output:

ALL ID      Store_id   Sub_store
26821         26821           
26821                   26821B
26823         26823     26823AV
26823                   26823B
26824                   26824DCF
1 Answers

Solution if empty values are missing values with Series.fillna and DataFrame.insert for new column to first position:

#if need all integers form start of Sub_store strings
s = df['Store_id'].fillna(df['Sub_store'].str.extract('(\d+)'), expand=False)
#if need first 5 letters
#s = df['Store_id'].fillna(df['Sub_store'].str[:5])
df.insert(0, 'ALL ID', s)

print (df)
  ALL ID Store_id Sub_store
0  26821    26821       NaN
1  26821      NaN    26821B
2  26823    26823   26823AV
3  26823      NaN    26823B
4  26824      NaN  26824DCF

Solution if missing values are empty strings with Series.mask:

s = df['Store_id'].mask(df['Store_id'] == '', df['Sub_store'].str.extract('(\d+)',expand=False))
df.insert(0, 'ALL ID', s)

print (df)
  ALL ID Store_id Sub_store
0  26821    26821          
1  26821             26821B
2  26823    26823   26823AV
3  26823             26823B
4  26824           26824DCF
Related