Pandas一个需求:存在一个列表,需要在一个DataFrame中取到以该列表为索引的数据
2021/5/24 10:31:00
本文主要是介绍Pandas一个需求:存在一个列表,需要在一个DataFrame中取到以该列表为索引的数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
需求:Pandas一个需求:存在一个列表,需要在一个DataFrame中取到以该列表为索引的数据
这里有一个坑,
In [103]: s = pd.Series([1, 2, 3]) In [104]: s Out[104]: 0 1 1 2 2 3 dtype: int64 当loc[]中的列表包含于S的索引中的话,没有问题
In [105]: s.loc[[1, 2]] Out[105]: 1 2 2 3 dtype: int64
In [4]: s.loc[[1, 2, 3]]
Passing list-likes to .loc with any non-matching elements will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
由于 3不在s的索引中,所以引发了一个错误。
解决办法:
将s先用reindex() 接收需索引的列表, 这样就会将s索引中没有的值,填充为Nan
In [106]: s.reindex([1, 2, 3]) Out[106]: 1 2.0 2 3.0 3 NaN dtype: float64 另外:如果你只想取到给定list和DataFrame索引中交集的值,那么就可以用一下方式:
In [107]: labels = [1, 2, 3] In [108]: s.loc[s.index.intersection(labels)] Out[108]: 1 2 2 3 dtype: int64 同时需要注意:
这篇关于Pandas一个需求:存在一个列表,需要在一个DataFrame中取到以该列表为索引的数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)