everestial
everestial

Reputation: 7255

How to convert specific columns values in pandas to list?

In the following pandas Dataframe:

alfa  alfa_id    beta    beta_id
ak   23          ji    24
bc   24          kl    25

I want to convert the columns alfa and beta to list.

cols = [l for l in df.columns.values if not l.endswith('id')]
df = df[cols].applymap(lambda c:[list(c)])
# gives me

Output I am getting now:

print(df)

alfa      beta    
[[a, k]]  [[j, i]] 

** But, Expected output is:**

alfa      alfa_id    beta       beta_id
[[a, k]]   23        [[j, i]]    24

PS note: I could have done

df = df.applymap(lambda c:[list(c)] if type(c) is str else c)

But, I don't want this because there will be some other columns which should not be converted to list. So, I wanted to make cols values specifically which needs to be converted to list.

Thanks,

Upvotes: 2

Views: 424

Answers (1)

piRSquared
piRSquared

Reputation: 294238

setup

cols = ['alfa', 'beta']

new answer

df.assign(**df[cols].stack().apply(list).unstack().to_dict('list'))

     alfa  alfa_id    beta  beta_id
0  [a, k]       23  [j, i]       24
1  [b, c]       24  [k, l]       25

old answers

option 1

df[cols].applymap(list)

option 2

df[cols].stack().apply(list).unstack()

yield

     alfa    beta
0  [a, k]  [j, i]
1  [b, c]  [k, l]

Upvotes: 2

Related Questions