df_每月交易新=pd.DataFrame(index=df_每月交易.index,columns=df_每月交易.columns)
df_每月交易新.astype('object')
for i in range(0,1821):
for j in range (0,11):
if j==0:
if df_每月交易.iloc[i,j]==1:
df_每月交易新.iloc[i,j]=='new'
else:
df_每月交易新.iloc[i,j]=='unreg'
else:
if df_每月交易.iloc[i,j]==1 and df_每月交易.iloc[i,:j].sum==1:
df_每月交易新.iloc[i,j]=='new'
if df_每月交易新.iloc[i,j+1]=='new':
df_每月交易新.iloc[i,:j]=='unreg'
if df_每月交易新.iloc[i,j-1]=='new'and df_每月交易.iloc[i,j]==1:
df_每月交易新.iloc[i,j]=='active'
if df_每月交易新.iloc[i,j-1]=='new'and df_每月交易.iloc[i,j]==0:
df_每月交易新.iloc[i,j]=='unactive'
if df_每月交易新.iloc[i,j-1]=='active'and df_每月交易.iloc[i,j]==1:
df_每月交易新.iloc[i,j]=='active'
if df_每月交易新.iloc[i,j-1]=='unactive'and df_每月交易.iloc[i,j]==0:
df_每月交易新.iloc[i,j]=='unactive'
if df_每月交易新.iloc[i,j-1]=='unactive'and df_每月交易.iloc[i,j]==1:
df_每月交易新.iloc[i,j]=='return'
df_每月交易新
IndexError Traceback (most recent call last)
<ipython-input-91-d09f16334459> in <module>
10 if df_每月交易.iloc[i,j]==1 and df_每月交易.iloc[i,:j].sum==1:
11 df_每月交易新.iloc[i,j]=='new'
---> 12 if df_每月交易新.iloc[i,j+1]=='new':
13 df_每月交易新.iloc[i,:j]=='unreg'
14 if df_每月交易新.iloc[i,j-1]=='new'and df_每月交易.iloc[i,j]==1:
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key)
1470 except (KeyError, IndexError):
1471 pass
-> 1472 return self._getitem_tuple(key)
1473 else:
1474 # we by definition only have the 0th axis
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
2011 def _getitem_tuple(self, tup):
2012
-> 2013 self._has_valid_tuple(tup)
2014 try:
2015 return self._getitem_lowerdim(tup)
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key)
220 raise IndexingError('Too many indexers')
221 try:
--> 222 self._validate_key(k, i)
223 except ValueError:
224 raise ValueError("Location based indexing can only have "
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis)
1955 return
1956 elif is_integer(key):
-> 1957 self._validate_integer(key, axis)
1958 elif isinstance(key, tuple):
1959 # a tuple should already have been caught by this point
~\Anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_integer(self, key, axis)
2007 l = len(ax)
2008 if key >= l or key < -l:
-> 2009 raise IndexError("single positional indexer is out-of-bounds")
2010
2011 def _getitem_tuple(self, tup):
IndexError: single positional indexer is out-of-bounds
# 对消费状况打标签
def active_status(data):
status=[]
for i in range(12):
#若本月无消费
if data[i] == 1:
if len(status) > 0:
if status[i-1] == 'unreg':
status.append('new') #新用户
elif status[i-1] == 'unactive':
status.append('return') #回流用户
else:
status.append('active') #活跃用户
else:
status.append('new')
#若本月有消费
else:
if len(status) > 0:
if status[i-1] == 'unreg': #未注册
status.append('unreg')
else:
status.append('unactive')#不活跃
else:
status.append('unreg')
return pd.Series(status)
pivoted_status=df_每月交易.iloc[:,1:12].apply(active_status,axis=1)
pivoted_status.columns= df_每月交易.columns
pivoted_status
KeyError Traceback (most recent call last)
<ipython-input-92-954111c930c9> in <module>
26
27
---> 28 pivoted_status=df_每月交易.iloc[:,1:12].apply(active_status,axis=1)
29
30
~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
6012 args=args,
6013 kwds=kwds)
-> 6014 return op.get_result()
6015
6016 def applymap(self, func):
~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
140 return self.apply_raw()
141
--> 142 return self.apply_standard()
143
144 def apply_empty_result(self):
~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
246
247 # compute the result using the series generator
--> 248 self.apply_series_generator()
249
250 # wrap results
~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self)
275 try:
276 for i, v in enumerate(series_gen):
--> 277 results[i] = self.f(v)
278 keys.append(v.name)
279 except Exception as e:
<ipython-input-92-954111c930c9> in active_status(data)
4 for i in range(12):
5 #若本月无消费
----> 6 if data[i] == 1:
7 if len(status) > 0:
8 if status[i-1] == 'unreg':
~\Anaconda3\lib\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\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.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: (0, 'occurred at index 178')
python判断客户每月活跃状态提示key erro和IndexError怎么解决
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
守护者170 2024-02-22 10:13关注出现 "Key Error" 和 "Index Error" 的错误提示意味着你正在尝试使用一个不存在的键或索引来访问字典或列表等数据结构。
为了解决这些问题,可以采取以下步骤:- 检查键或索引是否存在:首先,确保你要访问的键或索引在数据结构中存在。可以通过打印相关数据结构的内容来检查。
- 检查键或索引的命名:确认所使用的键或索引的命名是否正确,要与数据结构中存储的键或索引名称相匹配。
- 防止越界访问:如果出现 "Index Error",请确保你尝试访问的索引没有超出数据结构的范围。索引应该从 0 开始,而且不能大于结构的长度减去 1。
- 处理异常:使用异常处理机制捕获这些错误,可以使用 try-except 语句来捕获 KeyError 和 IndexError,并提供相应的处理方式。例如,你可以在捕获到键或索引错误时输出一个错误消息或执行其他适当的操作。
通过以上步骤,应该能够解决 "Key Error" 和 "Index Error" 错误,并根据具体情况采取适当的操作。
解决 无用评论 打赏 举报