向Python中的现有数据帧添加新列

向Python中的现有数据帧添加新列,python,pandas,dataframe,chained-assignment,Python,Pandas,Dataframe,Chained Assignment,我有以下索引数据框,其中命名的列和行不是连续的数字: 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',并且不想更改数据框中的任何内容(即,新列始终与数据框具有相同的长度)

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

          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'
,并且不想更改数据框中的任何内容(即,新列始终与数据框具有相同的长度)

如何将列
e
添加到上述示例中

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

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

注意:我最初(非常老)的建议是使用
map
(这要慢得多):

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

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

注意:我最初(非常老)的建议是使用
map
(这要慢得多):


编辑2017

如注释和@Alexander所述,当前将系列值添加为数据帧的新列的最佳方法可以使用:


编辑2015
一些报告使用此代码获得了设置为CopyWarning的

但是,该代码在当前的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'] = pd.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

>>> pd.version.short_version
'0.16.1'
设置WithCopyWarning
旨在通知数据帧副本上可能无效的赋值。它不一定说你做错了(它可能会引发误报),但从0.13.0开始,它会让你知道有更多适合同样目的的方法。然后,如果您收到警告,只需遵循它的建议:尝试使用.loc[row\u index,col\u indexer]=value

事实上,这是目前最有效的方法


原始答复:

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

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

编辑2017

如注释和@Alexander所述,当前将系列值添加为数据帧的新列的最佳方法可以使用:


编辑2015
一些报告使用此代码获得了设置为CopyWarning的

但是,该代码在当前的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'] = pd.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

>>> pd.version.short_version
'0.16.1'
设置WithCopyWarning
旨在通知数据帧副本上可能无效的赋值。它不一定说你做错了(它可能会引发误报),但从0.13.0开始,它会让你知道有更多适合同样目的的方法。然后,如果您收到警告,只需遵循它的建议:尝试使用.loc[row\u index,col\u indexer]=value

事实上,这是目前最有效的方法


原始答复:

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

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

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

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

但是需要注意的一点是,如果

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)

但有一件事需要注意,如果你这样做了

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)

我使用copywarning获得了可怕的
设置,但它并没有通过使用iloc语法修复。我的数据框是由来自ODBC源的read_sql创建的。根据以上lowtech的建议,以下内容对我有效:

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))
在末尾插入列效果很好。我不知道这是否是最有效的,但我不喜欢警告信息。我认为有更好的解决方案,但我找不到,我认为这取决于索引的某些方面。
注意。这只工作一次,如果试图覆盖现有列,将显示错误消息。
注意如上所述,从0.16.0开始分配是最佳解决方案。见文件
适用于不覆盖中间值的数据流类型。

我使用copyWarning获得了可怕的
设置,并且它不是通过使用iloc语法修复的。我的数据框是由来自ODBC源的read_sql创建的。根据以上lowtech的建议,以下内容对我有效:

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))
在末尾插入列效果很好。我不知道这是否是最有效的,但我不喜欢警告信息。我认为有更好的解决方案,但我找不到,我认为这取决于索引的某些方面。
注意。这只工作一次,如果试图覆盖现有列,将显示错误消息。
注意如上所述,从0.16.0开始分配是最佳解决方案。见文件
适用于不覆盖中间值的数据流类型。

在指定新列之前,如果有索引数据,则需要对索引进行排序。至少就我而言,我必须:

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

在分配新列之前,如果有索引数据,则需要对索引进行排序。至少就我而言,我必须:

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

以下是我所做的。。。但我对熊猫和蟒蛇都是新手,所以没有承诺

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)

以下是我所做的。。。但我对熊猫和蟒蛇都是新手,所以没有承诺

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)

让我补充一下,就像,
一样,
没有用copywarning解决
设置问题,我不得不求助于
df.insert()
。在我的例子中,假阳性是由“假”链索引
dict['a']['e']
生成的,其中
'e'
是新列,
dict['a']
是来自字典的数据帧

另外请注意,如果您知道自己在做什么,可以使用
pd.options.mode.chained\u分配
df = df.copy()
df['col_name'] = values
 df1.loc[:,'e'] = Series(np.random.randn(sLength))
col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})
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
    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
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
df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values
df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))
df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)
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(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(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=pd.Series(['no', 'no', 'no', 'yes'])
TypeError: assign() got multiple values for keyword argument 'self'
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)
df.loc[:, 'NewCol'] = 'New_Val'
df = pd.DataFrame(data=np.random.randn(20, 4), columns=['A', 'B', 'C', 'D'])

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
3  -0.147354  0.778707  0.479145  2.284143
4  -0.529529  0.000571  0.913779  1.395894
5   2.592400  0.637253  1.441096 -0.631468
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
8   0.606985 -2.232903 -1.358107 -2.855494
9  -0.692013  0.671866  1.179466 -1.180351
10 -1.093707 -0.530600  0.182926 -1.296494
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
18  0.693458  0.144327  0.329500 -0.655045
19  0.104425  0.037412  0.450598 -0.923387


df.drop([3, 5, 8, 10, 18], inplace=True)

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
4  -0.529529  0.000571  0.913779  1.395894
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
9  -0.692013  0.671866  1.179466 -1.180351
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
19  0.104425  0.037412  0.450598 -0.923387

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

df
           A         B         C         D  NewCol
0  -0.761269  0.477348  1.170614  0.752714       0
1   1.217250 -0.930860 -0.769324 -0.408642       0
2  -0.619679 -1.227659 -0.259135  1.700294       0
4  -0.529529  0.000571  0.913779  1.395894       0
6   0.757178  0.240012 -0.553820  1.177202       0
7  -0.986128 -1.313843  0.788589 -0.707836       0
9  -0.692013  0.671866  1.179466 -1.180351       0
11 -0.143273 -0.503199 -1.328728  0.610552       0
12 -0.923110 -1.365890 -1.366202 -1.185999       0
13 -2.026832  0.273593 -0.440426 -0.627423       0
14 -0.054503 -0.788866 -0.228088 -0.404783       0
15  0.955298 -1.430019  1.434071 -0.088215       0
16 -0.227946  0.047462  0.373573 -0.111675       0
17  1.627912  0.043611  1.743403 -0.012714       0
19  0.104425  0.037412  0.450598 -0.923387       0
df["new_columns_name"]=series_variable_name #this will do it for you
data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values
DataFrame.insert(loc, column, value)
e = [-0.335485, -1.166658, -0.385571]    
DataFrame.insert(loc=len(df.columns), column='e', value=e)
df['i'] = None
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()
x=pd.DataFrame([1,2,3,4,5])

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

z=pd.concat([x,y],axis=1)
df.loc[:, 'e'] = pd.Series()
df = df.assign(new_col=lambda x:10)  # x is each row passed in to the lambda func
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