ChatGPT解决这个技术问题 Extra ChatGPT

如何向现有 DataFrame 添加新列?

我有以下索引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

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

如果您的新列依赖于您现有的列,那么您可以在下面添加新列。
哇,这个问答真是一团糟。直截了当的答案是 df['e'] = e,但如果索引不匹配,这不起作用,但索引不匹配,因为 OP 是这样创建的 (e = Series(<np_array>)),但这已从问题中删除修订版 5。

j
joaquin

编辑 2017

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

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

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

>>> pd.version.short_version
'0.16.1'

SettingWithCopyWarning 旨在通知 Dataframe 副本上可能无效的分配。它不一定说你做错了(它可能会触发误报),但从 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
>>> 

事实上,这是目前更有效的方法,如 described in pandas docs

原答案:

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

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

如果您需要在列前添加 DataFrame.insert:df1.insert(0, 'A', Series(np.random.randn(sLength), index=df1.index))
从 Pandas 0.12 版开始,我认为这种语法不是最优的,并给出警告:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead
跟随 .loc 作为 SettingWithCopy 警告以某种方式导致更多警告: ... self.obj[item_labels[indexer[info_axis]]] = value
@toto_tico 您可以解压缩 kwargs 字典,如下所示:df1 = df1.assign(**{'e': p.Series(np.random.randn(sLength)).values})
不要说“当前”或引用年份,而是引用 pandas 版本号,例如“0.14-0.16 之间做 X,在 0.17+ 做 Y...”
K
Kathirmani Sukumar

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


尽管投票数很高:这个答案是错误的。请注意,OP 有一个具有非连续索引的数据框,并且 e (Series(np.random.randn(sLength))) 生成一个系列 0-n 索引。如果你把它分配给 df1 那么你会得到一些 NaN 单元格。
@joaquin 说的是真的,但只要你牢记这一点,这是一个非常有用的捷径。
@Eric Leschinski:不确定您如何编辑对这个问题有帮助。 my_dataframe = pd.DataFrame(columns=('foo', 'bar'))。还原您的编辑
它没有帮助,因为如果您有多行并且您使用分配,它会为新列的所有行分配该值(在您的情况下为 e),这通常是不可取的。
上面提出的@joaquin 问题可以通过执行以下操作简单地解决(如上面 joaquin 的回答):df['e'] = e.values 或等效的 df['e'] = e.to_numpy()。正确的?
f
fantabolous

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

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

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

df['e'] = e.values

分配(熊猫 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 中找到首次引入此新功能时的说明。


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

超级简单的列分配

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 [] = 方法尝试 变得“聪明”

究竟发生了什么。

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

边注

这很快就会导致认知失调,因为 []= 方法会根据输入尝试做很多不同的事情,除非您只知道 pandas 的工作原理,否则无法预测结果。因此,我建议不要在代码库中使用 []=,但在笔记本中探索数据时,这很好。

绕过问题

如果您有一个 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 正在悄悄地执行外部连接或外部合并”。这是整个主题中最重要的信息。但是您能否提供有关 []= 运算符如何工作的官方文档的链接?
S
Sociopath

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

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

它不会产生 SettingWithCopyWarning


从上面复制@smci 的评论......不要说“当前”或参考年份,请参考 Pandas 版本号
P
Peter Mortensen

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

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

请注意,我最初的(非常旧的)建议是使用 map(速度要慢得多):

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

感谢您的回复,正如我已经给出的那样,我可以修改您的代码 .map 以使用现有系列而不是 lambda 吗?我尝试 df1['e'] = df1['a'].map(lambda x: e)df1['e'] = df1['a'].map(e) 但这不是我需要的。 (我是pyhon的新手,你之前的回答已经帮助了我)
@tomasz74 如果您已经将 e 作为系列,那么您不需要使用 map,使用 df['e']=e(@joaquins 回答)。
D
DKMDebugin

最简单的方法:-

data['new_col'] = list_of_values

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

这样,您可以在 pandas 对象中设置新值时避免所谓的链式索引。 Click here to read further


d
digdug

如果您想将整个新列设置为初始基值(例如 None),您可以这样做:df1['e'] = None

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


这引发了带有复制警告的设置
如果有人想添加一个空列,df['E'] = '' 也可以使用
h
hum3

我得到了可怕的 SettingWithCopyWarning,它没有通过使用 iloc 语法来修复。我的 DataFrame 是由 read_sql 从 ODBC 源创建的。使用上面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 适用于不覆盖中间值的数据流类型。


S
Sociopath

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


我真的不明白,为什么这不是首选答案。如果您有 pd.Series,tolist() 命令可能会有所帮助。
OP 有一个系列 e,向 df 添加列的方式与添加列表不同。上面的答案很好地解释了在这种情况下该怎么做,尤其是@firelynx 答案。以下答案大多不知道这一点....
G
Georgy

创建一个空列

df['i'] = None

h
halfelf

如果您尝试添加的列是系列变量,则只需:

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

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


P
Psidom

如果数据框和 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

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

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

K
K88

万无一失:

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

不是万无一失的。这并没有解决 OP 的问题,即现有数据帧和新系列的索引未对齐的情况。
P
Peter Mortensen

不过要注意的一件事是,如果你这样做

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)

N
Nooyi

要在数据框中的给定位置(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)

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

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


C
Community

让我补充一下,就像对于 hum3.loc 没有解决 SettingWithCopyWarning,我不得不求助于 df.insert()。在我的情况下,误报是由“假”链索引 dict['a']['e'] 生成的,其中 'e' 是新列,dict['a'] 是来自字典的 DataFrame。

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


D
Dima Lituiev

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

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

C
Chirag

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

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

它还给出了警告信息
你应该使用 df1.loc[::,'e'] = Series(np.random.randn(sLength))
C
Community

我一直在寻找一种将一列 numpy.nan 添加到数据框中而不得到愚蠢 SettingWithCopyWarning 的通用方法。

从以下:

这里的答案

这个关于将变量作为关键字参数传递的问题

这种用于在线生成 NaN 的 numpy 数组的方法

我想出了这个:

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

M
MaxU - stop genocide of UA

为了完整起见 - 使用 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

A
Alexander Myasnikov

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

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

P
Peter Mortensen

以下是我所做的......但我对熊猫和真正的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)

A
Aseem

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

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

df 现在将在所有行中具有 value=10 的新列“new_col”。


T
Tushar

如果您获得 SettingWithCopyWarning,一个简单的解决方法是复制您尝试添加列的 DataFrame。

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

这不是一个好主意。如果数据框足够大,它将是内存密集型的......此外,如果您每隔一段时间继续添加列,它将变成一场噩梦。
4
4b0
x=pd.DataFrame([1,2,3,4,5])

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

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

https://i.stack.imgur.com/Hu5To.jpg


我怀疑这是否有帮助 - 甚至根本有效。介意解释吗?
h
hansrajswapnil

这是向 pandas 数据框添加新列的特殊情况。在这里,我基于数据框的现有列数据添加了一个新功能/列。

因此,让我们的 dataFrame 包含列“feature_1”、“feature_2”、“probability_score”,我们必须根据“probability_score”列中的数据添加一个新的“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()

G
GOPI A.R
import pandas as pd

# Define a dictionary containing data
data = {'a': [0,0,0.671399,0.446172,0,0.614758],
    'b': [0,0,0.101208,-0.243316,0,0.075793],
    'c': [0,0,-0.181532,0.051767,0,-0.451460],
    'd': [0,0,0.241273,1.577318,0,-0.012493]}

# Convert the dictionary into DataFrame
df = pd.DataFrame(data)

# Declare a list that is to be converted into a column
col_e = [-0.335485,-1.166658,-0.385571,0,0,0]


df['e'] = col_e

# add column 'e'
df['e'] = col_e

# Observe the result
df

https://i.stack.imgur.com/huVhM.jpg


我们可以尝试使用 insert 或 assign() 方法.... df.insert(4, "e", [-0.335485,-1.166658,-0.385571,0,0,0], True) (or) df = df.分配(e = [-0.335485,-1.166658,-0.385571,0,0,0])
d
dna-data

每当您将 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

https://i.stack.imgur.com/Xrbei.png


E
Ersin Gülbahar

您可以通过 for 循环插入新列,如下所示:

for label,row in your_dframe.iterrows():
      your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])

示例代码在这里:

import pandas as pd

data = {
  "any_of_column_in_your_dframe" : ["ersingulbahar","yagiz","TS"],
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

#load data into a DataFrame object:
your_dframe = pd.DataFrame(data)


for label,row in your_dframe.iterrows():
      your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])
      
      
print(your_dframe) 

输出在这里:

any_of_column_in_your_dframe 卡路里持续时间 new_column_length ersingulbahar 420 50 13.0 yagiz 380 40 5.0 TS 390 45 2.0

不是:你也可以这样使用:

your_dframe["new_column_length"]=your_dframe["any_of_column_in_your_dframe"].apply(len)