python – 确定列的累积最大值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 确定列的累积最大值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2673字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试以下代码
df = pd.DataFrame([[23, 52], [36, 49], [52, 61], [75, 82], [97, 12]], columns=['A', 'B'])
df['C'] = np.where(df['A'] > df['C'].shift(), df['A'], df['C'].shift())
print(df)
假设第一个df [‘C] .shift()操作应该假设为0(因为df [‘C’]不存在)
预期产出
A B C
0 23 52 23
1 36 49 36
2 12 61 36
3 75 82 75
4 70 12 75
但我得到一个KeyError异常.
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\pandas\core\indexes\base.py", line 2442, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5280)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126)
File "pandas\_libs\hashtable_class_helper.pxi", line 1210, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20523)
File "pandas\_libs\hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20477)
KeyError: 'C'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Development\workspace\TestPython\TestPython.py", line 6, in <module>
df['C'] = np.where(df['A'] > df['C'].shift(), df['B'].shift(), df['A'])
File "C:\Program Files\Python36\lib\site-packages\pandas\core\frame.py", line 1964, in __getitem__
return self._getitem_column(key)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\frame.py", line 1971, in _getitem_column
return self._get_item_cache(key)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\generic.py", line 1645, in _get_item_cache
values = self._data.get(item)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\internals.py", line 3590, in get
loc = self.items.get_loc(item)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\indexes\base.py", line 2444, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5280)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126)
File "pandas\_libs\hashtable_class_helper.pxi", line 1210, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20523)
File "pandas\_libs\hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20477)
KeyError: 'C'
根据我的理解,这种情况正在发生,因为C列第一次不存在,所以移动列会抛出此异常.
我的问题是有另一种解决这个问题的方法吗?
解决方法:
你需要cummax:
df['C'] = df.A.cummax()
内容总结
以上是互联网集市为您收集整理的python – 确定列的累积最大值全部内容,希望文章能够帮你解决python – 确定列的累积最大值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。
来源:【匿名】