gpt4 book ai didi

python - 当每一列都是数组时如何应用数据框

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:20 24 4
gpt4 key购买 nike

我有一个训练数据集,其中单词列表中的一列。下面的例子

    target   id     values
0 eng 123 ['hi', 'hello','bye']
1 eng 124 ['my', 'name', 'is']

现在我有一个 clean (text) 函数,我想将它应用到 values 列。我在下面试过

train = pd.read_json('./file.json')
train['values'] = train['values'].apply(clean)

出现错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我知道我正在将 .apply 应用于不允许但不确定如何修复它的字符串数组。

请推荐

编辑:添加清理(文本)功能

def clean(text):
import re
from string import punctuation
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords

def pad_str(s):
return ' '+s+' '

if pd.isnull(text):
return ''


# Empty question

if type(text) != str or text=='':
return ''

# Clean the text
text = re.sub("\'s", " ", text)
text = re.sub(" whats ", " what is ", text, flags=re.IGNORECASE)
#many other regular expression operations



# replace non-ascii word with special word
text = re.sub('[^\x00-\x7F]+', pad_str(SPECIAL_TOKENS['non-ascii']), text)
return text

最佳答案

问题出在您的 clean 函数上。此函数正在处理一个字符串,而不是一个字符串列表,但您正在将一个字符串列表传递给它。你应该这样做:

train['values'] = train['values'].apply(lambda x: [clean(s) for s in x])

关于python - 当每一列都是数组时如何应用数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com