Bird
Raised Fist0
PandasHow-ToBeginner · 3 min read

How to Use Values in pandas: Syntax and Examples

In pandas, you can use the values attribute on a DataFrame or Series to get the underlying data as a NumPy array. This is useful when you want to perform operations that require raw array data instead of pandas objects.
📐

Syntax

The values attribute is used without parentheses on a pandas DataFrame or Series to extract the data as a NumPy array.

  • DataFrame.values: Returns a 2D NumPy array of the DataFrame's data.
  • Series.values: Returns a 1D NumPy array of the Series' data.
python
array = df.values
array_series = series.values
💻

Example

This example shows how to create a pandas DataFrame and Series, then use values to get their underlying NumPy arrays.

python
import pandas as pd

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)

# Create a Series
series = pd.Series([10, 20, 30])

# Get underlying numpy arrays
df_values = df.values
series_values = series.values

print('DataFrame values:')
print(df_values)
print('\nSeries values:')
print(series_values)
Output
DataFrame values: [['Alice' 25] ['Bob' 30] ['Charlie' 35]] Series values: [10 20 30]
⚠️

Common Pitfalls

One common mistake is expecting values to preserve pandas index or column labels. It does not; it returns only raw data as a NumPy array without labels.

Also, for newer pandas versions, it is recommended to use to_numpy() instead of values for better consistency and options.

python
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['x', 'y'])

# Using values loses index and columns
print('Using values:')
print(df.values)

# Using to_numpy() is preferred
print('\nUsing to_numpy():')
print(df.to_numpy())
Output
Using values: [[1 3] [2 4]] Using to_numpy(): [[1 3] [2 4]]
📊

Quick Reference

Summary tips for using values in pandas:

  • Use values to get raw NumPy arrays from DataFrames or Series.
  • Labels (index/columns) are not included in the output.
  • Prefer to_numpy() for more control and future compatibility.
  • Useful for integrating pandas data with NumPy or other libraries.
✅

Key Takeaways

Use values to extract raw NumPy arrays from pandas DataFrames or Series.
values returns data without index or column labels.
Prefer to_numpy() over values for better future support.
Extracted arrays are useful for NumPy operations or other libraries needing raw data.