【问题标题】:Don't I need a double bracket when I am accessing a column to apply a lamda function in python?当我访问列以在 python 中应用 lamda 函数时,我不需要双括号吗?
【发布时间】:2022-01-25 17:53:31
【问题描述】:

下面的代码从 DataFrame 的“文本”列中提取一个句子(字符串),并用空格替换任何非字母数字字符(即#、?. 1. 等)。我一直以为 由于“文本”是一列,我需要在每一侧使用双括号。当我添加时,我得到了下面的错误。单括号不是指行吗?由于“文本”是一列 我不需要双括号吗?

data['text'] = data['text'].apply((lambda x: re.sub\
('[^a-zA-Z0-9\s]','',x))) 

在 (x) 24 #删除特殊字符 25 data[['text']] = data[['text']].apply((lambda x: re.sub
---> 26 ('[^a-zA-Z0-9\s]','',x))) 27

~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags) 190 一个可调用对象,它传递了 Match 对象并且必须返回 191 要使用的替换字符串。""" --> 192 return _compile(pattern, flags).sub(repl, string, count) 193 194 def subn(模式,repl,字符串,count=0,flags=0):

TypeError: ('expected string or bytes-like object', 'occured at index text')

【问题讨论】:

  • 你真的不需要在这里使用 lambda。看看在 pandas 中使用字符串访问器。 pandas working with text 并替换为 pandas string methods
  • 感谢 Scott,但我的问题真正旨在找出为什么我不需要双括号来访问列(以及为什么双括号会给我一个错误)。
  • 使用单括号,您将 pd.Series 传递给 apply 函数,当您使用双括号时,您将 pd.Dataframe 传递给 apply 函数。如果您的 lambda 函数是为处理 pd.Series 而编写的,那么在传递单列数据帧时双括号将出错。

标签: python dataframe lambda


【解决方案1】:

单括号产生一个 pd.Series,双括号产生一个单列数据框。

df = pd.DataFrame({'Col1':[1,2,3,4]})

type(df['Col1']) # <class 'pandas.core.series.Series'>

type(df[['Col1']]) # <class 'pandas.core.frame.DataFrame'>

你的 lambda 函数被设计成手一个 pd.Series。

让我们编写一个自定义函数来分析传递了什么。

def f(x):
    print(type(x))
    return x

df['Col1'].apply(f)

输出:

<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>

“int”类表明,当在 pd.Series 上调用 apply 时,该系列中的每个元素都会传递给 apply 中的函数。

相对于单列数据框:

df[['Col1']].apply(f)

输出:

<class 'pandas.core.series.Series'>

这表明每个数据框列(一个pd.Series)都传递给apply中的函数。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多