返回带有其他列的pandas数据帧

时间:2016-11-27 01:17:35

标签: python pandas dataframe

我有一个数据框列表,我想创建一个与前一个数据框相同的新数据框列表,但是使用功能方法添加了一列。

这是我的想法和我尝试过的:

# 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]

2 个答案:

答案 0 :(得分:2)

使用assign()方法:

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

答案 1 :(得分:1)

您可以使用.assign()方法以功能方式创建具有额外列的新数据框:

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