【发布时间】:2018-02-19 16:20:15
【问题描述】:
我有一个数据框 cleaned_bp['VISITCODE'],它看起来像:
0 1
1 2
2 3
3 6
4 9
5 12
6 15
非索引列由字符串组成。 我想通过这样做将它们转换为整数:
for i in range(len(cleaned_bp['VISITCODE'])):
cleaned_bp['VISITCODE'][i] = int(cleaned_bp['VISITCODE'][i])
但我收到此错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-42-4d6508c1abda> in <module>()
1 for i in range(len(cleaned_bp['VISITCODE'])):
----> 2 cleaned_bp['VISITCODE'][i] = int(cleaned_bp['VISITCODE'][i])
~/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
599 key = com._apply_if_callable(key, self)
600 try:
--> 601 result = self.index.get_value(self, key)
602
603 if not is_scalar(result):
~/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
2475 try:
2476 return self._engine.get_value(s, k,
-> 2477 tz=getattr(series.dtype, 'tz', None))
2478 except KeyError as e1:
2479 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: 13
我在这里做错了什么?
【问题讨论】:
-
有什么理由不只使用
cleaned_bp['VISITCODE'].astype(int)或pandas.to_numeric吗? -
@JonClements 不知道他们。会使用它们。仍然很好奇为什么问题中的方法不起作用
-
因为
cleaned_np['VISITCODE'][i]将尝试访问与列相关的index - 而不是position,就像它是一个列表一样。这意味着您的索引列与range(len(your_df))不同...如果您将其更改为iloc[i]它会起作用...您可能需要阅读索引。
标签: python pandas dataframe type-conversion