lundi 20 juillet 2020

In Python Pandas, how do I combine two columns containing strings using if/else statement or similar?

I have created a pandas dataframe from an excel file where first two columns are:

df = pd.DataFrame({'0':['','','Location Code','pH','Ag','Alkalinity'], '1':['Lab Id','Collection Date','','','µg/L','mg/L']})

which looks like this:

         df[0]           df[1]
                        Lab Id
               Collection Date
Location Code                 
           pH                 
           Ag             µg/L
   Alkalinity             mg/L

I want to merge these columns into one that looks like this:

           df[0]
          Lab Id
 Collection Date
   Location Code
              pH
        Ag (µg/L)
Alkalinity (mg/L)

I believe I need a control statement before combining df[0] and df[1] which would appear like this:

if **there is a blank space in either column, then it performs**:
   df[0] = df[0].astype(str)+df[1].astype(str)
else:
   df[0] = df[0].astype(str)+' ('+df[1].astype(str)+')'

but I am not sure how to write the if statement. Could anyone please guide me here. Thank you very much.

Aucun commentaire:

Enregistrer un commentaire