mask and concatenate two string series in pandas

Viewed 239

I am struggling to get this to work. I am masking out the NaN's then concatenating the two series. Is it not possible to concatenation using + in this way? If not what is the best way?

    row_mask = df[df[win_end].notnull()]
    df.loc[row_mask, df['window_full']] = df.loc[row_mask, win_start]+' - '+df.loc[row_mask, win_end]
    print(df['window_start', 'window_end', 'window_full'])

input

win_start     win_end
2021-12-16    2021-12-18
2022-01-19    NaN
2022-01-18    2022-01-20

expected output

win_start     win_end        window_full
2021-12-16    2021-12-18     2021-12-16 - 2021-12-18
2022-01-19    NaN            NaN
2022-01-18    2022-01-20     2022-01-18 - 2022-01-20

error

ValueError: Cannot index with multidimensional key

EDIT

Thanks for your quick reply. So I tried that using 'window_full' but still getting an error:-

ValueError: Cannot index with multidimensional key

EDIT 2 working solution required bool mask to be passed:-

row_mask = df['win_end'].notnull()
df.loc[row_mask, 'window_full'] = (df.loc[row_mask, 'win_start']+' - '+df.loc[row_mask, 'win_end'])

1 Answers

For assign new column use column name instead Series df['window_full'], same like syntax like selecting, also is necessary pass boolean mask instead filtered DataFrame row_mask = df[df[win_end].notnull()]:

row_mask = df['win_end'].notnull()
df.loc[row_mask, 'window_full'] = (df.loc[row_mask, 'win_start']+' - '+
                                   df.loc[row_mask, 'win_end'])

Or test both columns:

row_mask = df[['win_end', win_start]].notnull().any(axis=1)
df.loc[row_mask, 'window_full'] = (df.loc[row_mask, 'win_start']+' - '+
                                   df.loc[row_mask, 'win_end'])
Related