Reputation: 7255
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
alfa_id and beta_id
are lost but I want them back in one line code (as simple as possible).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
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