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 数组进行标记并将其分配给数据数组。
解决方案
如前所述,KeyError
意味着您正在访问该列表中不存在的键(索引)。
最重要的是,我相信您可以简化此代码:
for i in range(len(X)):
data[i]=tokenize(X[i])
通过做这个:
data = [tokenize(i) for i in X]
推荐阅读
- autodesk-forge - Autodesk Forge 的 Reality Capture API 生成的高程图 geotiff 的内容是什么?
- c# - C#中的SQL Server多命令异常捕获
- c++ - Qtimer 不工作。我认为它没有更新
- android - 使用 Xdebug 在 nextcloud 中调试文件下载功能时超时
- ios - 将 applicationIconBadgeNumber 设置为零时,iOS 徽章未清除
- python - 一些python包本质上是全球性的吗?
- typescript - 如何编写 PickByValue 类型?
- css - 粘性页脚在短页面上强制置于底部
- javascript - 如何在画布中将图像绘制为画笔描边
- mongodb - 在不关闭数据库的情况下在 Mongo 中删除 5TB 集合