Reputation: 18416
Suppose I have following pandas' Series:
series=pd.Series(data=['A', 'B'], index=[2,3])
I can get the first value using .iloc
as series.iloc[0] #output: 'A'
Or, I can just use the get
method passing the actual index value like series.get(2) #output: 'A'
But is there any way to pass iloc
like indexing to get
method to get the first value in the series?
>>> series.get(0, '')
'' # Expected 'A', the first value for index 0
One way is to just reset the index and drop it then to call get
method:
>>> series.reset_index(drop=True).get(0, '')
'A'
Is there any other function similar to get
method (or a way to use get
method) that allows passing iloc
like index, without the overhead of resetting the index?
EDIT: Please be noted that this series comes from dataframe masking so this series can be empty, that is why I intentionally added default value as empty string ''
for get
method.
Upvotes: 1
Views: 357
Reputation: 862691
Use next
with iter
if need first value also with empty Series:
next(iter(series), None)
Upvotes: 1
Reputation: 50864
What about using head
to get the first row and take the value from there?
series.head(1).item() # A
Upvotes: 1
Reputation: 1658
Is this what you have in mind or not really?
series.get(series.index[0])
Upvotes: 1