2

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
  • The columns for alfa_id and beta_id are lost but I want them back in one line code (as simple as possible).
  • I am looking for a method which also keeps the memory foot print low.

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,

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I think I confused you with the output I am expecting. Actually, I want the alfa_id and others_id back into the dataframe in a memory efficient way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.