How to join two columns of a pandas dataframe containing null values?

Viewed 47

I have the dataframe pandas:

      import numpy as np
      import pandas as pd

      df = pd.DataFrame({'ID': [1,2,3,4,5],
                         'column_1': [10.6, 10.4, np.NaN, np.NaN, np.NaN],
                         'column_2': [np.NaN, np.NaN, 30, 40, 50]
                        })

     print(df)

     ID column_1    column_2
      1  10.6        NaN
      2  10.4        NaN
      3  NaN         30.0
      4  NaN         40.0
      5  NaN         50.0

I would like to create a new column in the dataframe that is the junction of columns 1 and 2. So I tried to do the following code:

      df['column_1'] = df['column_1'].astype(float)
      df['column_2'] = df['column_2'].astype(float)


      df['new_column'] = [''.join(i) for i in zip(df['column_1'],
                                                  df['column_2'])]

However, when I run mine to create the new column, the following error appears: TypeError: sequence item 0: expected str instance, float found

Note: I tried using astype() to convert the columns to the float type, but the problem continues. How can I solve it?

I would like the output to be:

       ID   column_1    column_2   new_columns
        1      10.6      NaN         10.6
        2      10.4      NaN         10.4
        3      NaN       30.0        30.0
        4      NaN       40.0        40.0
        5      NaN       50.0        50.0
1 Answers
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'ID': [1,2,3,4,5],
    'column_1': [10.6, 10.4, np.NaN, np.NaN, np.NaN],
    'column_2': [np.NaN, np.NaN, 30, 40, 50]
})

df['column_1'] = df['column_1'].astype(float)
df['column_2'] = df['column_2'].astype(float)

df['new_column'] = df['column_1'].combine_first(df['column_2'])

print(df)

Result:

   ID  column_1  column_2  new_column
0   1      10.6       NaN        10.6
1   2      10.4       NaN        10.4
2   3       NaN      30.0        30.0
3   4       NaN      40.0        40.0
4   5       NaN      50.0        50.0
Related