Python 返回带有附加列的dataframe
我有一个dataframes列表,我想创建一个新的dataframes列表,该列表与前一个列表相同,但使用函数方法添加了一列 以下是我的想法和我的尝试:Python 返回带有附加列的dataframe,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个dataframes列表,我想创建一个新的dataframes列表,该列表与前一个列表相同,但使用函数方法添加了一列 以下是我的想法和我的尝试: # 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 modi
# 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]
您可以使用.assign()
方法以功能性方式创建具有额外列的新数据帧:
[df.assign(new_column = lambda _: True) for df in dfs]
使用以下方法:
[df.assign(new_column = True) for df in dfs]