在Python pandas中向现有DataFrame添加新列

时间:2012-09-23 19:00:01

标签: python pandas dataframe chained-assignment

我有以下索引的DataFrame,其命名列和行不是连续数字:

          a         b         c         d
2  0.671399  0.101208 -0.181532  0.241273
3  0.446172 -0.243316  0.051767  1.577318
5  0.614758  0.075793 -0.451460 -0.012493

我想在现有数据框中添加一个新列'e',并且不希望更改数据框中的任何内容(即,新列的长度始终与DataFrame相同)。

0   -0.335485
1   -1.166658
2   -0.385571
dtype: float64

我尝试了joinappendmerge的不同版本,但我没有得到我想要的结果,最多只有错误。如何在上面的示例中添加列e

29 个答案:

答案 0 :(得分:879)

使用原始df1索引创建系列:

df1['e'] = Series(np.random.randn(sLength), index=df1.index)

编辑2015
有些人报告使用此代码获取SettingWithCopyWarning 但是,代码仍然与当前的pandas版本0.16.1完美匹配。

>>> sLength = len(df1['a'])
>>> df1
          a         b         c         d
6 -0.269221 -0.026476  0.997517  1.294385
8  0.917438  0.847941  0.034235 -0.448948

>>> df1['e'] = p.Series(np.random.randn(sLength), index=df1.index)
>>> df1
          a         b         c         d         e
6 -0.269221 -0.026476  0.997517  1.294385  1.757167
8  0.917438  0.847941  0.034235 -0.448948  2.228131

>>> p.version.short_version
'0.16.1'

SettingWithCopyWarning旨在通知Dataframe副本上可能无效的分配。它并不一定表示你做错了(它可以触发误报)但是从0.13.0开始它会让你知道有更多适当的方法用于同一目的。然后,如果您收到警告,请按照其建议:尝试使用.loc [row_index,col_indexer] = value而不是

>>> df1.loc[:,'f'] = p.Series(np.random.randn(sLength), index=df1.index)
>>> df1
          a         b         c         d         e         f
6 -0.269221 -0.026476  0.997517  1.294385  1.757167 -0.050927
8  0.917438  0.847941  0.034235 -0.448948  2.228131  0.006109
>>> 

事实上,这是目前比described in pandas docs

更有效的方法

编辑2017

如评论和@Alexander所示,目前将系列值添加为DataFrame新列的最佳方法可能是使用assign

df1 = df1.assign(e=p.Series(np.random.randn(sLength)).values)

答案 1 :(得分:185)

这是添加新列的简单方法:df['e'] = e

答案 2 :(得分:128)

  

我想在现有数据框中添加一个新列' e'并且不会更改数据框中的任何内容。 (该系列的长度始终与数据帧相同。)

我假设e中的索引值与df1中的索引值匹配。

启动名为e的新列的最简单方法,并为其分配系列e中的值:

df['e'] = e.values

指定(Pandas 0.16.0 +)

从Pandas 0.16.0开始,您还可以使用assign,它将新列分配给DataFrame并返回一个新对象(副本),除了新的列之外还包含所有原始列。

df1 = df1.assign(e=e.values)

根据this example(还包括assign函数的源代码),您还可以包含多个列:

df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
>>> df.assign(mean_a=df.a.mean(), mean_b=df.b.mean())
   a  b  mean_a  mean_b
0  1  3     1.5     3.5
1  2  4     1.5     3.5

在您的示例的上下文中:

np.random.seed(0)
df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = pd.Series(np.random.randn(sLength))

>>> df1
          a         b         c         d
0  1.764052  0.400157  0.978738  2.240893
2 -0.103219  0.410599  0.144044  1.454274
3  0.761038  0.121675  0.443863  0.333674
7  1.532779  1.469359  0.154947  0.378163
9  1.230291  1.202380 -0.387327 -0.302303

>>> e
0   -1.048553
1   -1.420018
2   -1.706270
3    1.950775
4   -0.509652
dtype: float64

df1 = df1.assign(e=e.values)

>>> df1
          a         b         c         d         e
0  1.764052  0.400157  0.978738  2.240893 -1.048553
2 -0.103219  0.410599  0.144044  1.454274 -1.420018
3  0.761038  0.121675  0.443863  0.333674 -1.706270
7  1.532779  1.469359  0.154947  0.378163  1.950775
9  1.230291  1.202380 -0.387327 -0.302303 -0.509652

首次引入此新功能的说明可以在here找到。

答案 3 :(得分:44)

直接通过NumPy执行此操作将是最有效的:

df1['e'] = np.random.randn(sLength)

请注意我的原始(非常古老)建议是使用map(速度要慢得多):

df1['e'] = df1['a'].map(lambda x: np.random.random())

答案 4 :(得分:44)

在最近的Pandas版本中,似乎可以使用df.assign

df1 = df1.assign(e=np.random.randn(sLength))

它不会产生SettingWithCopyWarning

答案 5 :(得分:29)

超级简单的列分配

pandas数据框实现为列的有序字典。

这意味着__getitem__ []不仅可用于获取特定列,还可以使用__setitem__ [] =分配新列。

例如,只需使用[]访问者

,此数据框就可以添加一列
    size      name color
0    big      rose   red
1  small    violet  blue
2  small     tulip   red
3  small  harebell  blue

df['protected'] = ['no', 'no', 'no', 'yes']

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

请注意,即使数据框的索引处于关闭状态,这仍然有效。

df.index = [3,2,1,0]
df['protected'] = ['no', 'no', 'no', 'yes']
    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

[] =是要走的路,但要小心!

但是,如果您有一个pd.Series并尝试将其分配给索引关闭的数据框,那么您将遇到麻烦。见例:

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'])
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

这是因为默认情况下pd.Series具有从0到n枚举的索引。并且大熊猫[] =方法尝试 为“智能”

实际发生了什么。

当你使用[] =方法时,pandas正在使用左手数据帧的索引和右手系列的索引安静地执行外连接或外连接。 df['column'] = series

旁注

这很快导致认知失调,因为[]=方法试图根据输入做很多不同的事情,除非你只知道熊猫怎么做,否则无法预测结果作品。因此,我建议不要在代码库中使用[]=,但在笔记本中浏览数据时,它很好。

解决问题

如果您有pd.Series并希望从上到下分配,或者您正在编写生产代码并且您不确定索引顺序,那么保护此类问题是值得的。

您可以将pd.Series向下转换为np.ndarraylist,这样就可以了。

df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values

df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))

但这不是很明确。

有些程序员可能会说:“嘿,这看起来很多余,我只会优化它”。

显式方式

pd.Series的索引设置为df的索引是明确的。

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)

或者更现实地说,您可能已经有pd.Series

protected_series = pd.Series(['no', 'no', 'no', 'yes'])
protected_series.index = df.index

3     no
2     no
1     no
0    yes

现在可以分配

df['protected'] = protected_series

    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

使用df.reset_index()

的替代方式

由于索引不一致是问题所在,如果你觉得数据框的索引应该没有规定的东西,你可以简单地删除索引,这应该更快,但它不是很干净,因为你的功能现在可能做了两件事。

df.reset_index(drop=True)
protected_series.reset_index(drop=True)
df['protected'] = protected_series

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

关于df.assign

的说明

虽然df.assign使您更清楚地了解自己在做什么,但它实际上存在与上述[]=

相同的所有问题
df.assign(protected=pd.Series(['no', 'no', 'no', 'yes']))
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

请注意df.assign您的专栏未被称为self。这会导致错误。这会使df.assign 发臭,因为函数中存在这些工件。

df.assign(self=pd.Series(['no', 'no', 'no', 'yes'])
TypeError: assign() got multiple values for keyword argument 'self'

你可能会说,“好吧,我不会再使用self”。但是谁知道这个函数将来如何变化以支持新的论点。也许你的列名将成为新的pandas更新中的一个参数,导致升级问题。

答案 6 :(得分:22)

如果要将整个新列设置为初始基值(例如None),可以执行以下操作:df1['e'] = None

这实际上会将“对象”类型分配给单元格。所以稍后你可以自由地将复杂的数据类型(如list)放入单个单元格中。

答案 7 :(得分:18)

最简单的方法:-

data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values

答案 8 :(得分:18)

我遇到了可怕的SettingWithCopyWarning,并且没有使用iloc语法修复它。我的DataFrame是由ODBC源的read_sql创建的。使用上述lowtech的建议,以下内容对我有用:

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))

这样可以在最后插入列。我不知道它是否是最有效的,但我不喜欢警告信息。我认为有一个更好的解决方案,但我找不到它,我认为这取决于指数的某些方面 的。这仅适用一次,如果尝试覆盖现有列,则会给出错误消息 注意如上所述,从0.16.0分配是最佳解决方案。参见文档http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html#pandas.DataFrame.assign 适用于不覆盖中间值的数据流类型。

答案 9 :(得分:11)

  1. 首先创建一个包含相关数据的python list_of_e
  2. 使用此:     df['e'] = list_of_e

答案 10 :(得分:10)

如果您要添加的列是一个系列变量,那么只需:

df["new_columns_name"]=series_variable_name #this will do it for you

即使您要替换现有列,这也很有效。只需键入与要替换的列相同的new_columns_name。它将使用新系列数据覆盖现有列数据。

答案 11 :(得分:9)

set.seed(1) min <- 3 vec <- rpois(20, 1) vec #> 0 1 1 2 0 2 3 1 1 0 0 0 1 1 2 1 1 4 1 2 table(vec) #> vec #> 0 1 2 3 4 #> 5 9 4 1 1

简单易用的方法

e = [ -0.335485, -1.166658, -0.385571]

答案 12 :(得分:9)

<强>防呆:

github "ArtSabintsev/Siren"

示例:

df.loc[:, 'NewCol'] = 'New_Val'

答案 13 :(得分:8)

如果数据框和系列对象具有 相同的索引 pandas.concat也适用于此处:

import pandas as pd
df
#          a            b           c           d
#0  0.671399     0.101208   -0.181532    0.241273
#1  0.446172    -0.243316    0.051767    1.577318
#2  0.614758     0.075793   -0.451460   -0.012493

e = pd.Series([-0.335485, -1.166658, -0.385571])    
e
#0   -0.335485
#1   -1.166658
#2   -0.385571
#dtype: float64

# here we need to give the series object a name which converts to the new  column name 
# in the result
df = pd.concat([df, e.rename("e")], axis=1)
df

#          a            b           c           d           e
#0  0.671399     0.101208   -0.181532    0.241273   -0.335485
#1  0.446172    -0.243316    0.051767    1.577318   -1.166658
#2  0.614758     0.075793   -0.451460   -0.012493   -0.385571

如果他们没有相同的索引:

e.index = df.index
df = pd.concat([df, e.rename("e")], axis=1)

答案 14 :(得分:6)

我要补充一点,就像hum3一样,.loc没有解决SettingWithCopyWarning而我不得不诉诸df.insert()。在我看来,假阳性是由&#34;假的&#34;链索引dict['a']['e'],其中'e'是新列,dict['a']是来自字典的DataFrame。

另请注意,如果您知道自己在做什么,可以使用以下方式切换警告 pd.options.mode.chained_assignment = None 而不是使用此处给出的其他解决方案之一。

答案 15 :(得分:6)

但有一点需要注意的是,如果你这样做了

df1['e'] = Series(np.random.randn(sLength), index=df1.index)

这实际上是df1.index上的连接。因此,如果您想要外部连接效果,我可能不完美的解决方案是创建一个数据框,其索引值覆盖数据范围,然后使用上面的代码。例如,

data = pd.DataFrame(index=all_possible_values)
df1['e'] = Series(np.random.randn(sLength), index=df1.index)

答案 16 :(得分:6)

在分配新列之前,如果您有索引数据,则需要对索引进行排序。至少在我的情况下,我不得不:

data.set_index(['index_column'], inplace=True)
"if index is unsorted, assignment of a new column will fail"        
data.sort_index(inplace = True)
data.loc['index_value1', 'column_y'] = np.random.randn(data.loc['index_value1', 'column_x'].shape[0])

答案 17 :(得分:5)

我一直在寻找一种向数据框添加numpy.nan列的常规方法,而不会让愚蠢的SettingWithCopyWarning

以下内容:

我想出了这个:

col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})

答案 18 :(得分:4)

为了完整起见 - 使用DataFrame.eval()方法的另一种解决方案:

数据:

In [44]: e
Out[44]:
0    1.225506
1   -1.033944
2   -0.498953
3   -0.373332
4    0.615030
5   -0.622436
dtype: float64

In [45]: df1
Out[45]:
          a         b         c         d
0 -0.634222 -0.103264  0.745069  0.801288
4  0.782387 -0.090279  0.757662 -0.602408
5 -0.117456  2.124496  1.057301  0.765466
7  0.767532  0.104304 -0.586850  1.051297
8 -0.103272  0.958334  1.163092  1.182315
9 -0.616254  0.296678 -0.112027  0.679112

解决方案:

In [46]: df1.eval("e = @e.values", inplace=True)

In [47]: df1
Out[47]:
          a         b         c         d         e
0 -0.634222 -0.103264  0.745069  0.801288  1.225506
4  0.782387 -0.090279  0.757662 -0.602408 -1.033944
5 -0.117456  2.124496  1.057301  0.765466 -0.498953
7  0.767532  0.104304 -0.586850  1.051297 -0.373332
8 -0.103272  0.958334  1.163092  1.182315  0.615030
9 -0.616254  0.296678 -0.112027  0.679112 -0.622436

答案 19 :(得分:4)

将新列“e”添加到现有数据框

 df1.loc[:,'e'] = Series(np.random.randn(sLength))

答案 20 :(得分:3)

如果您获得SettingWithCopyWarning,则可以轻松修复您尝试添加列的DataFrame。

df = df.copy()
df['col_name'] = values

答案 21 :(得分:3)

以下是我的所作所为...但我对熊猫和Python一般都很陌生,所以没有承诺。

df = pd.DataFrame([[1, 2], [3, 4], [5,6]], columns=list('AB'))

newCol = [3,5,7]
newName = 'C'

values = np.insert(df.values,df.shape[1],newCol,axis=1)
header = df.columns.values.tolist()
header.append(newName)

df = pd.DataFrame(values,columns=header)

答案 22 :(得分:3)

如果我们想为 df 中新列的所有行分配一个缩放值,例如:10:

df = df.assign(new_col=lambda x:10)  # x is each row passed in to the lambda func

df 现在将有新列 'new_col',所有行中的值都为 10。

答案 23 :(得分:1)

要在数据框中的给定位置(0 <= loc <=列数)插入新列,只需使用Dataframe.insert:

DataFrame.insert(loc, column, value)

因此,如果要在名为 df 的数据框的末尾添加 e 列,您可以使用:

e = [-0.335485, -1.166658, -0.385571]    
DataFrame.insert(loc=len(df.columns), column='e', value=e)

可以是一个系列,整数(在这种情况下,所有单元格都填充有一个值)或类似数组的结构

blog

答案 24 :(得分:1)

这是在熊猫数据框中添加新列的一种特殊情况。在这里,我将基于数据框的现有列数据添加一个新的功能/列。

因此,让我们的dataFrame具有列'feature_1','feature_2','probability_score'列,我们必须基于列'probability_score'中的数据添加一个new_column'predicted_class'。

我将使用python中的map()函数,并定义自己的函数,该函数将实现有关如何为dataFrame中的每一行赋予特定的class_label的逻辑。

data = pd.read_csv('data.csv')

def myFunction(x):
   //implement your logic here

   if so and so:
        return a
   return b

variable_1 = data['probability_score']
predicted_class = variable_1.map(myFunction)

data['predicted_class'] = predicted_class

// check dataFrame, new column is included based on an existing column data for each row
data.head()

答案 25 :(得分:0)

要创建一个空列

// Change the url to include item Socks when clicked

window.location.search += '&socks3B%2D=22'

答案 26 :(得分:0)

x=pd.DataFrame([1,2,3,4,5])

y=pd.DataFrame([5,4,3,2,1])

z=pd.concat([x,y],axis=1)

enter image description here

答案 27 :(得分:0)

如果您只需要创建一个新的空列,那么最短的解决方案是:

df.loc[:, 'e'] = pd.Series()

答案 28 :(得分:0)

每当您将 Series 对象作为新列添加到现有 DF 时,您需要确保它们都具有相同的索引。 然后将其添加到 DF

e_series = pd.Series([-0.335485, -1.166658,-0.385571])
print(e_series)
e_series.index = d_f.index
d_f['e'] = e_series
d_f

enter image description here

相关问题