无法将数组分配给其他数组

2024-04-26 11:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能用for循环将一个数组分配给另一个数组。下面是我的代码示例。你知道吗

df = pd.read_csv('20-newsgroups-ciphertext-challenge/train.csv')
data_1 = df.query('difficulty==1')
X = data_1.iloc[:,-2]
y = data_1.iloc[:,-1]

def tokenize(text): 
    return text.split("1")

data = X
print(type(data))
print(type(X))
for i in range(len(X)):
    data[i]=tokenize(X[i])

下面是错误代码。我对此一无所知。你知道吗

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-32-4637ad724b98> in <module>
     19 print(type(X))
     20 for i in range(len(X)):
---> 21     data[i]=tokenize(X[i])
     22 
     23 #print(data.head)

~/anaconda3/lib/python3.7/site-packages/pandas/core/series.py in __getitem__(self, key)
    765         key = com._apply_if_callable(key, self)
    766         try:
--> 767             result = self.index.get_value(self, key)
    768 
    769             if not is_scalar(result):

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   3116         try:
   3117             return self._engine.get_value(s, k,
-> 3118                                           tz=getattr(series.dtype, 'tz', None))
   3119         except KeyError as e1:
   3120             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

我是python的新手,这里的情况似乎很简单,但我希望能找到解决方案。 我希望X数组被标记化并将其分配给数据数组。


Tags: keyinselfpandasfordatagetindex
3条回答

迭代数据帧的方式是错误的

for i in data.columns :         
    data[i] = data[i].apply(lambda x: tokenize(x))

你甚至不需要X

打印循环中的iX[i],而不是将其发送到tokenize()函数:KeyError意味着您无法访问Xith元素。你知道吗

如前所述,KeyError表示您正在访问一个列表中不存在的键(索引)。你知道吗

除此之外,我相信您可以简化此代码:

for i in range(len(X)):
    data[i]=tokenize(X[i])

通过这样做:

data = [tokenize(i) for i in X]

相关问题 更多 >