首页 > 解决方案 > 字典如 get() 在 pandas Series 上,索引值如 iloc

问题描述

假设我有以下熊猫系列:

series=pd.Series(data=['A', 'B'], index=[2,3])

.iloc我可以使用as获得第一个值series.iloc[0] #output: 'A'

或者,我可以使用get传递实际索引值的方法,例如series.get(2) #output: 'A'

但是有什么方法可以iloc像索引一样传递给get方法来获取系列中的第一个值?

>>> series.get(0,  '')
''     # Expected 'A', the first value for index 0

一种方法是仅重置索引并将其删除然后调用get方法:

>>> series.reset_index(drop=True).get(0,  '')
'A'

是否有任何其他类似于get方法(或使用方法的get 方法)的函数允许传递iloc类似的索引,而无需重置索引的开销?

编辑:请注意,这个系列来自数据框屏蔽,所以这个系列可以是空的,这就是为什么我故意添加默认值作为方法的空''字符串get

标签: pythonpandas

解决方案


这是你的想法还是不是真的?

series.get(series.index[0])


推荐阅读