首页 > 解决方案 > 无法将数组分配给另一个数组

问题描述

我无法使用 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 数组进行标记并将其分配给数据数组。

标签: python

解决方案


如前所述,KeyError意味着您正在访问该列表中不存在的键(索引)。

最重要的是,我相信您可以简化此代码:

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

通过做这个:

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

推荐阅读