Nora
Nora

Reputation: 1

Concatenate multiple columns and skip blanks

I want to concatenate 8 columns to one. There are a lot of blanks in each column. I want to skip or just not showing the blanks in the combined column.

I tried this code:

df['combined']=df.apply(
                        lambda x:'%s_%s_%s_%s_%s_%s_%s_%s'
                          % (x['a'],x['b'],x['c'],x['d'],x['e'],x['f'],x['g'],x['h']),
                        axis=1)

The result is as following:

combined
0
1
2        type1
3
4        type2
5
6        type8
...

I want to delete the leading numbers and the blanks. I am expecting to get the combined column like 'type1type2type8'

Upvotes: 0

Views: 1242

Answers (2)

john
john

Reputation: 1036

The code below can avoid missing values -

df['combined'] = df.apply( lambda x: x['a':'h'].str.cat(sep='_'), axis=1 )

Upvotes: 1

ugn
ugn

Reputation: 89

I would:
df['combined'] = df.apply( lambda x: x['a':'h'].str.concat(sep='_'), axis=1 ).
has the benefit of built in nan handling... and avoid the acane-ness of agg()

Upvotes: 0

Related Questions