Dataframe 在对一列文本进行标记化之后,如何将该标记化输出(将作为一个数组)重新分配到数据帧中的同一列?
这里有一个问题,我正在标记数据帧的一列。在将标记化输出分配给列之前,它会在索引2处显示完美的标记化输出。但当我尝试将其分配给数据帧时。它只在dataframe的索引处分配数组的第一个元素,即50。谁能解释发生了什么事?或者我错在哪里 以下是标记数据帧列的方法 这是我正在计算的输出!Dataframe 在对一列文本进行标记化之后,如何将该标记化输出(将作为一个数组)重新分配到数据帧中的同一列?,dataframe,machine-learning,deep-learning,nlp,Dataframe,Machine Learning,Deep Learning,Nlp,这里有一个问题,我正在标记数据帧的一列。在将标记化输出分配给列之前,它会在索引2处显示完美的标记化输出。但当我尝试将其分配给数据帧时。它只在dataframe的索引处分配数组的第一个元素,即50。谁能解释发生了什么事?或者我错在哪里 以下是标记数据帧列的方法 这是我正在计算的输出! 请根据我们自己的经验,使您的代码尽可能重复 您的问题是希望将列表列表作为列分配给数据帧。下面是重现您的问题的代码 如果运行上面的代码,您将看到您尝试分配令牌列表的列只获取每个列表中的第一个令牌作为其值。就我个人而言
from typing import List
def concat_tokenized(check: List[List[int]]) -> List[str]:
"""Turn all values in a list into a string
and return a list of string"""
new_check = [[str(x) for x in y] for y in check] # turn each element of a list into a string
new_check = ["".join(x) for x in new_check] # concatenate elements in each list into a string
return new_check
def deconcat_tokenized(string: List[str]) -> List[List[int]]:
"""Return list of lists of int from a list of string"""
new_x = [int(x) for x in string]
return new_x
print(concat_tokenized(check))
print(df["texts"].apply(deconcat_tokenized))
第一个函数将把列表中的每个列表转换为字符串。因此,您将得到一个字符串列表,这些字符串可以作为列分配给数据帧。最后,为了获得原始值,将第二个函数应用于数据帧的每一行。它不适用于整个列
import pandas as pd
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
def makeToken(text_col):
tokenizer = Tokenizer(num_words=10, oov_token="OOV")
tokenizer.fit_on_texts(text_col)
# Encode training data sentences into sequences
train_sequences = tokenizer.texts_to_sequences(text_col)
# Get max training sequence length
maxlen = max([len(x) for x in train_sequences])
pad_seq = pad_sequences(train_sequences, padding="post", truncating="post", maxlen=maxlen)
return pad_seq
texts = {"texts":["hello worrld", "goody bye", "good morning"],
"numbers": [1, 2, 3]}
df = pd.DataFrame(texts)
#df
check = makeToken(df.texts)
df.texts = check
print(check)
print(df)
from typing import List
def concat_tokenized(check: List[List[int]]) -> List[str]:
"""Turn all values in a list into a string
and return a list of string"""
new_check = [[str(x) for x in y] for y in check] # turn each element of a list into a string
new_check = ["".join(x) for x in new_check] # concatenate elements in each list into a string
return new_check
def deconcat_tokenized(string: List[str]) -> List[List[int]]:
"""Return list of lists of int from a list of string"""
new_x = [int(x) for x in string]
return new_x
print(concat_tokenized(check))
print(df["texts"].apply(deconcat_tokenized))