0

Consider the below dataframe, column c will always have an empty list in it. I need to compute few things and add it to the list, for example append values of column a and b to the empty list of column c

Given df

enter image description here

Expected output:

enter image description here

3 Answers 3

1

Let's try

df["Mark list"] = df.filter(regex='Mark\d+').agg(list, axis=1)
Sign up to request clarification or add additional context in comments.

Comments

0

You'll want to use pandas.DataFrame.apply for this.

something like:

df["Mark list"] = df.apply(lambda row: [row["Mark1"], row["Mark2"]], axis=1)

1 Comment

Thanks for your reply!, one more question. If I have to append mark3 to the mark list how can it be done?
0

You could convert the columns you want to append into lists (using a custom function and apply) and then simply add them to the list column. This will work for columns calculated on the fly as well.

import pandas as pd

df_vals = {"mark1": [23, 34, 45], "mark2": [45, 34, 12], "mark_list": [[] for i in range(3)]}

to_list = lambda x: [x]
df = pd.DataFrame(df_vals)
df["mark_list"] += df["mark1"].apply(to_list)
df["mark_list"] += df["mark2"].apply(to_list)
df["mark_list"] += (df["mark2"] + df["mark1"]).apply(to_list)  # works for columns created on-the-fly
df

Output:

   mark1  mark2     mark_list
0     23     45  [23, 45, 68]
1     34     34  [34, 34, 68]
2     45     12  [45, 12, 57]

Comments

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.