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

tom*_*z74 887 python dataframe pandas 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
Run Code Online (Sandbox Code Playgroud)

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

0   -0.335485
1   -1.166658
2   -0.385571
dtype: float64
Run Code Online (Sandbox Code Playgroud)

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

joa*_*uin 963

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

df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
Run Code Online (Sandbox Code Playgroud)

编辑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'] = 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

>>> p.version.short_version
'0.16.1'
Run Code Online (Sandbox Code Playgroud)

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

>>> df1.loc[:,'f'] = pd.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
>>> 
Run Code Online (Sandbox Code Playgroud)

事实上,这是目前pandas docs中描述的更有效的方法



编辑2017

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

df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values)
Run Code Online (Sandbox Code Playgroud)

  • 从Pandas版本0.12开始,我相信这种语法不是最优的,并且会发出警告:`SettingWithCopyWarning:尝试在DataFrame的切片副本上设置一个值.尝试使用.loc [row_index,col_indexer] = value (26认同)
  • 如果你需要*prepend*列使用DataFrame.insert:df1.insert(0,'A',Series(np.random.randn(sLength),index = df1.index)) (21认同)
  • 请参考熊猫版本号,而不是说"当前"或引用年份,例如"0.14-0.16 do X,in 0.17+ do Y ..." (18认同)
  • @toto_tico你可以解压一个`kwargs`字典,如下所示:`df1 = df1.assign(**{'e':p.Series(np.random.randn(sLength)).values})` (11认同)
  • 以下.loc作为SettingWithCopy警告会以某种方式导致更多警告:... self.obj [item_labels [indexer [info_axis]]] = value (4认同)
  • 无需从numpy数组创建Series以将其重新转换回numpy数组:`df1 = df1.assign(e = np.random.randn(sLength))`更简单. (4认同)
  • @ Juanlu001有相同的代码吗?请看编辑 (2认同)
  • 是否有理由使用 df1 = df1.assign(e=e.values) 而不是 df1['e'] = e.values? (2认同)
  • 也许编辑这个问题,将最新/相关的答案/编辑放在顶部? (2认同)
  • 每当我看到有关该诅咒的“SettingWithCopyWarning”的讨论时,我的目光就会变得呆滞。 (2认同)
  • @ 4myle这个答案不断发展的事实看起来对熊猫开发者来说真的很糟糕.多年来两个基本的api变化 - 对他们来说并不是很好. (2认同)
  • 不会`assign` 复制整个DataFrame 吗?如果是,那不是超级低效吗? (2认同)
  • 初学者可能想知道代码中的`p`是什么。我建议显式地将pandas导入为pd(而不是p,因为pd在某种程度上是标准);例如,在这里使用:https://pandas.pydata.org/pandas-docs/stable/getting_started/10min .html) (2认同)

Kat*_*mar 203

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

  • 尽管票数很高:*这个答案是错误的*.注意,OP有一个带有非连续索引的数据帧,`e`(`Series(np.random.randn(sLength))`)生成一个索引的0-n系列.如果将此值分配给df1,则会获得一些NaN单元格. (140认同)
  • @joaquin所说的是真的,但只要你牢记这一点,这是一个非常有用的捷径. (29认同)
  • 注意:高反对率(现在为 1/6)(使用 `df['e'] = e.values` 代替) (4认同)
  • @Eric Leschinski:不确定您如何编辑对这个问题有帮助。`my_dataframe = pd.DataFrame(columns=('foo', 'bar'))`。还原您的编辑 (2认同)
  • 上面@joaquin提出的问题可以简单地通过执行以下操作来解决(就像上面joaquin的答案一样):`df['e'] = e.values`或等效地,`df['e'] = e.to_numpy()`。正确的? (2认同)

Ale*_*der 141

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

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

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

df['e'] = e.values
Run Code Online (Sandbox Code Playgroud)

分配(熊猫0.16.0+)

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

df1 = df1.assign(e=e.values)
Run Code Online (Sandbox Code Playgroud)

根据此示例(还包括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
Run Code Online (Sandbox Code Playgroud)

在您的示例的上下文中:

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
Run Code Online (Sandbox Code Playgroud)

可以在此处找到此新功能首次引入时的说明.

  • 考虑到第一种方法(`df ['e'] = e.values`)不会创建数据帧的副本,而第二种方法(使用`df.assign`),对这两种方法的相对性能有任何评论)呢?如果按顺序添加大量新列并且大数据帧,我希望第一种方法的性能要好得多. (2认同)
  • @jhin是的,如果您正在处理固定数据帧,那么直接分配显然很多.使用`assign`的好处是将您的操作链接在一起. (2认同)
  • 为了好玩`df.assign(** df.mean()。add_prefix('mean _'))` (2认同)
  • @Owlright 从问题来看,OP 似乎只是连接数据帧并忽略索引。如果是这种情况,上述方法将起作用。如果希望保留索引,则使用类似 `df_new = pd.concat([df1, df2], axis=1)` 之类的东西,注意默认情况下是 `ignore_index=False`。 (2认同)

Mik*_*bov 47

似乎在最近的Pandas版本中,要走的路是使用df.assign:

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

它不会产生SettingWithCopyWarning.

  • 从上面复制@smci 的评论......而不是说“当前”或引用年份,请参考 Pandas 版本号 (3认同)

And*_*den 45

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

df1['e'] = np.random.randn(sLength)
Run Code Online (Sandbox Code Playgroud)

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

df1['e'] = df1['a'].map(lambda x: np.random.random())
Run Code Online (Sandbox Code Playgroud)


fir*_*ynx 38

超级简单的列分配

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

但是,如果您有一个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
Run Code Online (Sandbox Code Playgroud)

这是因为pd.Series默认情况下,枚举的索引从0到n.而熊猫[] =方法试图 "聪明"

究竟是怎么回事.

当您使用该[] =方法时,pandas正在使用左侧数据帧的索引和右侧系列的索引安静地执行外部联接或外部合并.df['column'] = series

边注

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

绕过问题

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

你可以向下转换pd.Series为a np.ndarray或a list,这样就可以了.

df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values
Run Code Online (Sandbox Code Playgroud)

要么

df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))
Run Code Online (Sandbox Code Playgroud)

但这不是很明确.

一些程序员可能会说"嘿,这看起来多余,我只会优化它".

明确的方式

设置索引pd.Series的索引df是显式的.

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)
Run Code Online (Sandbox Code Playgroud)

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

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

3     no
2     no
1     no
0    yes
Run Code Online (Sandbox Code Playgroud)

现在可以分配

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
Run Code Online (Sandbox Code Playgroud)

替代方式 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
Run Code Online (Sandbox Code Playgroud)

注意 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
Run Code Online (Sandbox Code Playgroud)

请注意df.assign不要调用您的列self.这会导致错误.这有点df.assign ,因为函数中存在这些伪像.

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

你可能会说,"好吧,我self当时就不会用".但是谁知道这个函数将来如何变化以支持新的论点.也许您的列名将成为新的pandas更新中的参数,从而导致升级问题.

  • "_当你使用`[] =`方法时,pandas正在悄悄地执行外连接或外连接".这是整个主题中最重要的信息.但是,您是否可以提供有关`[] =`运算符如何工作的官方文档的链接? (5认同)

dig*_*dug 22

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

这实际上会将"对象"类型分配给单元格.所以稍后您可以将复杂的数据类型(如list)放入单个单元格中.

  • 这引发了一个带有复制警告的设置 (2认同)
  • df['E'] = '' 如果有人想添加一个空列也有效 (2认同)

小智 21

最简单的方法: -

data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values
Run Code Online (Sandbox Code Playgroud)


hum*_*um3 19

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

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))
Run Code Online (Sandbox Code Playgroud)

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


Sum*_*rel 13

  1. 首先创建一个list_of_e具有相关数据的python .
  2. 用这个: df['e'] = list_of_e


小智 13

创建空列

df['i'] = None
Run Code Online (Sandbox Code Playgroud)


Aks*_*hvi 11

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

df["new_columns_name"]=series_variable_name #this will do it for you
Run Code Online (Sandbox Code Playgroud)

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


小智 10

万全:

df.loc[:, 'NewCol'] = 'New_Val'
Run Code Online (Sandbox Code Playgroud)

例:

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
Run Code Online (Sandbox Code Playgroud)

  • 不是万无一失的。这并没有解决 OP 的问题,即现有数据帧和新系列的索引未对齐的情况。 (2认同)

Psi*_*dom 9

如果数据框和Series对象具有相同的索引,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
Run Code Online (Sandbox Code Playgroud)

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

e.index = df.index
df = pd.concat([df, e.rename("e")], axis=1)
Run Code Online (Sandbox Code Playgroud)


Noo*_*oyi 9

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

DataFrame.insert(loc, column, value)
Run Code Online (Sandbox Code Playgroud)

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

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

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

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html


Wil*_*llZ 6

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

df1['e'] = Series(np.random.randn(sLength), index=df1.index)
Run Code Online (Sandbox Code Playgroud)

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

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


Dim*_*iev 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])
Run Code Online (Sandbox Code Playgroud)


小智 6

让我补充一点,就像对于hum3一样,.loc没有解决问题SettingWithCopyWarning,我不得不诉诸df.insert().在我的情况下,误报是由"假"链索引生成的 dict['a']['e'],其中'e'是新列,并且dict['a']是来自字典的DataFrame.

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


Chi*_*rag 6

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

 df1.loc[:,'e'] = Series(np.random.randn(sLength))
Run Code Online (Sandbox Code Playgroud)


rya*_*lon 5

我一直在寻找一种将一列numpy.nans 添加到数据帧而不会变得愚蠢的一般方法SettingWithCopyWarning.

从以下内容:

  • 答案在这里
  • 关于将变量作为关键字参数传递的问题
  • 这种用于在线生成numpyNaN数组的方法

我想出了这个:

col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

为了完整起见 - 另一个使用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
Run Code Online (Sandbox Code Playgroud)

解决方案:

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
Run Code Online (Sandbox Code Playgroud)


Ale*_*kov 5

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

df.loc[:, 'e'] = pd.Series()
Run Code Online (Sandbox Code Playgroud)


小智 5

有 4 种方法可以将新列插入 pandas DataFrame:

  1. 简单的分配
  2. 插入()
  3. 分配()
  4. 连接()

让我们考虑以下示例:

import pandas as pd

df = pd.DataFrame({
    'col_a':[True, False, False], 
    'col_b': [1, 2, 3],
})
print(df)
    col_a  col_b
0   True     1
1  False     2
2  False     3
Run Code Online (Sandbox Code Playgroud)

使用简单的赋值

ser = pd.Series(['a', 'b', 'c'], index=[0, 1, 2])
print(ser)
0    a
1    b
2    c
dtype: object

df['col_c'] = pd.Series(['a', 'b', 'c'], index=[1, 2, 3])
print(df)
     col_a  col_b col_c
0   True     1  NaN
1  False     2    a
2  False     3    b
Run Code Online (Sandbox Code Playgroud)

使用分配()

e = pd.Series([1.0, 3.0, 2.0], index=[0, 2, 1])
ser = pd.Series(['a', 'b', 'c'], index=[0, 1, 2])
df.assign(colC=s.values, colB=e.values)
     col_a  col_b col_c
0   True   1.0    a
1  False   3.0    b
2  False   2.0    c
Run Code Online (Sandbox Code Playgroud)

使用插入()

df.insert(len(df.columns), 'col_c', ser.values)
print(df)
    col_a  col_b col_c
0   True     1    a
1  False     2    b
2  False     3    c
Run Code Online (Sandbox Code Playgroud)

使用 concat()

ser = pd.Series(['a', 'b', 'c'], index=[10, 20, 30])
df = pd.concat([df, ser.rename('colC')], axis=1)
print(df)
     col_a  col_b col_c
0    True   1.0  NaN
1   False   2.0  NaN
2   False   3.0  NaN
10    NaN   NaN    a
20    NaN   NaN    b
30    NaN   NaN    c
Run Code Online (Sandbox Code Playgroud)