Israelg99 Israelg99 - 6 months ago 51
Python Question

Return pandas dataframe with additional columns

I have a list of dataframes and I want to create a new list of dataframes that is identical to the previous one but with an added column using a functional approach.

Here's my thinking and what I've tried:

# I know this is possible. It will add a new column of True.
df['new_column'] = True

# However, it edits the dataframe, I want a functional approach that returns a new modified dataframe.
# Something like this.
df + ('new_column', True)

# Then I can use it in list comprehension. consider dfs is a list of dataframes.
[df + ('new_column', True) for df in dfs]


Use the assign() method:

[df.assign(new_column = True) for df in dfs]