Home > Blockchain >  append values to a empty list in a column
append values to a empty list in a column

Time:08-26

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

CodePudding user response:

Let's try

df["Mark list"] = df.filter(regex='Mark\d ').agg(list, axis=1)

CodePudding user response:

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)

CodePudding user response:

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]
  • Related