How to Access Series Values in pandas: Simple Guide
You can access values in a pandas
Series using the index label with series[label] or by position with series.iloc[position]. To get all values as a list or array, use series.values or series.to_list().Syntax
Here are common ways to access values in a pandas Series:
series[label]: Access value by index label.series.iloc[position]: Access value by integer position.series.values: Get all values as a NumPy array.series.to_list(): Convert all values to a Python list.
python
value_by_label = series[label] value_by_position = series.iloc[position] all_values_array = series.values all_values_list = series.to_list()
Example
This example shows how to create a pandas Series and access its values by label and position, and how to get all values as a list and array.
python
import pandas as pd # Create a Series with custom index labels series = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']) # Access value by label value_label = series['b'] # Access value by position value_position = series.iloc[2] # Get all values as NumPy array values_array = series.values # Get all values as list values_list = series.to_list() print(f"Value by label 'b': {value_label}") print(f"Value by position 2: {value_position}") print(f"All values as array: {values_array}") print(f"All values as list: {values_list}")
Output
Value by label 'b': 20
Value by position 2: 30
All values as array: [10 20 30 40]
All values as list: [10, 20, 30, 40]
Common Pitfalls
Common mistakes when accessing Series values include:
- Using a label that does not exist causes a
KeyError. - Using
ilocwith an out-of-range position causes anIndexError. - Confusing label-based
locwith position-basediloc.
Always check your Series index and length before accessing values.
python
import pandas as pd series = pd.Series([5, 10, 15], index=['x', 'y', 'z']) # Wrong: Accessing non-existing label # value = series['a'] # Raises KeyError # Correct: Check if label exists if 'a' in series.index: value = series['a'] else: value = None # Wrong: Accessing out-of-range position # value_pos = series.iloc[5] # Raises IndexError # Correct: Check position range if 5 < len(series): value_pos = series.iloc[5] else: value_pos = None
Quick Reference
| Method | Description | Example |
|---|---|---|
| Access by label | Get value using index label | series['label'] |
| Access by position | Get value using integer position | series.iloc[0] |
| Get all values as array | Returns NumPy array of values | series.values |
| Get all values as list | Returns Python list of values | series.to_list() |
Key Takeaways
Use series[label] to access values by index label safely.
Use series.iloc[position] to access values by integer position.
series.values returns a NumPy array of all values.
series.to_list() converts all values to a Python list.
Check index labels and positions to avoid KeyError or IndexError.