samthebrand
samthebrand

Reputation: 3090

How to concatenate pandas dataframe columns into iterable lists?

I'm working with a pandas dataframe with about 200 columns. Columns 31-73 look something like this:

31   32   33
NaN  NaN  Z
X    NaN  Z
NaN  NaN  NaN
NaN  Y    Z

What I hope to return is a new column that looks (something) like this:

new_col
[Z]
[X,Z]
[]
[Y,Z]

I'm close, but not quite there. This code:

data['new_col'] = data.ix[:, 30:73].fillna('').apply(lambda row: ','.join(map(str, row)), axis=1)

returns this:

new_col
,,Z
,X,,Z
,,,
,,Y,Z

How can I exclude unnecessary delimiters from the new concatenated list?

Upvotes: 4

Views: 974

Answers (1)

EdChum
EdChum

Reputation: 394239

You seem to have an errant value Nan which I'm assuming is NaN, anyway this should work:

In [24]:
df.apply(lambda x: [','.join(x.dropna())], axis=1)

Out[24]:
0      [Z]
1    [X,Z]
2       []
3    [Y,Z]
dtype: object

So in your case:

data['new_col'] = data.apply(lambda x: [','.join(x.dropna())], axis=1)

should work.

Upvotes: 3

Related Questions