Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append list element in pandas dataframe column depending on value of another column

Whenever I try to append to a list given some condition, the value ends up being None instead of the list with the appended value. Example:

# sample data
data = {"bool_col": [True, False, True, True, False]}
my_df = pd.DataFrame.from_dict(data)

# instantiate column of empty lists
my_df["list_col"] = [[] for r in range(len(my_df))]

# append value to list_col when bool_col is True
my_df["list_col"] = my_df.apply(lambda x: x["list_col"].append("truth!") if x["bool_col"] else [], axis=1)

my_df

I’ve tried wrapping x["list_col"] in list() prior to calling append() to no avail. I’m not sure how to do this while retaining whatever list values may already be present and appending a new one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your case: append() appends item to list in place and returns None, which is allocated to my_df["list_col"]. You want to return the list in your apply lambda.

Try this: my_df["list_col"] = my_df.apply(lambda x: x["list_col"] + ["truth!"] if x["bool_col"] else [], axis=1)

Output:

   bool_col  list_col
0      True  [truth!]
1     False        []
2      True  [truth!]
3      True  [truth!]
4     False        []

This should work for your usecase, since if I repeat the apply twice, I get

   bool_col          list_col
0      True  [truth!, truth!]
1     False                []
2      True  [truth!, truth!]
3      True  [truth!, truth!]
4     False                []
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading