python - 如何将函数的返回值写入 pandas 数据帧的新列

标签 python pandas dataframe apply

我有一个 pandas 数据框,其中包含一列字符串(以逗号分隔的子字符串)。我想删除一些子字符串并将剩余的子字符串写入同一数据帧中的新列。

我为此编写的代码如下所示:

def remove_betas(df):
    for index,row in df.iterrows():
        list= row['Column'].split(',')
        if 'substring' in list:
            list.remove('beta-lactam')
            New= (',').join(list)
        elif not 'substring' in list:
            New= (',').join(Gene_list)
    return New
    df['NewColumn'].iloc[index]=New






 df.apply(remove_betas, axis=1)

当我运行它时,我的新列仅包含零。此代码背后的想法是获取 df 中每一行的每个字符串,以逗号将其拆分为子字符串,并在结果列表中搜索我想要删除的子字符串。删除后,我将列表重新连接成一个字符串,并将其写入 df 的新列,与相应行的索引位置相同。

我必须更改什么才能以所需的方式将生成的子字符串写入新列?

编辑

顺便说一下,我尝试编写一个 lambda 表达式,如 how to compute a new column based on the values of other columns in pandas - python 所示。 ,但我无法真正弄清楚如何在矢量化函数中完成所有操作。

我还尝试将子字符串替换为空(如 df.column.replace('x,?', '') ,但这不起作用,因为我必须稍后对列表进行计数。因此必须删除子字符串,如 list.remove('substring')

最佳答案

为什么不采用单行正则表达式解决方案:

import re

df = pd.DataFrame({'col1':[3,4,5],'col2':['a,ben,c','a,r,ben','cat,dog'],'col3':[1,2,3]})

#In [220]: df
#Out[220]:
#   col1     col2  col3
#0     3  a,ben,c     1
#1     4  a,r,ben     2
#2     5  cat,dog     3

df['new'] = df.col2.apply(lambda x: re.sub(',?ben|ben,?', '', x))

#In [222]: df
#Out[222]:
#   col1     col2  col3      new
#0     3  a,ben,c     1      a,c
#1     4  a,r,ben     2      a,r
#2     5  cat,dog     3  cat,dog

或者只是使用替换:

In [272]: df.col2.str.replace(',?ben|ben,?', '',case=False)
Out[272]:
0        a,c
1        a,r
2    cat,dog
Name: col2, dtype: object

关于python - 如何将函数的返回值写入 pandas 数据帧的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201725/

相关文章:

Python:根据用户输入打印一个或多个文件(副本)

python - 使用行为进行 API 端点测试

python - 如果 RAM 接近饱和,如何终止 Python 进程(Windows 上的 Anaconda)?

python - 如何根据其他列中的条件对 pandas 的 Dataframe 列进行操作

r - 在 ggplot 中对数据进行分组之前添加 geom_smooth()

python - 想要每个月的最后一天作为 pandas 中的数据框

python - 使用 None 值过滤 Pyspark 数据框列

python - 什么更有效率?使用 .replace() 或将字符串传递给列表

Python SQL 通过多个查询循环变量

python - 如何在 python : numpy. Mean() 中将多个列表合并为一个列表