将Pandas DataFrame转换为h2o.H2OFrame时出现AttributeError:'DataFrame'对象没有'as_matrix'属性
Ah, I’ve dealt with this exact headache before—let’s get this sorted out for you.
What’s causing the error?
Pandas deprecated the as_matrix() method way back in version 0.23, and completely removed it starting with Pandas 1.0.0. If you’re seeing this error, it’s either:
- You’re explicitly using
as_matrix()in your own code, or - Your installed version of H2O is outdated and still relies on this removed Pandas method.
Solutions to fix it
1. If you’re calling as_matrix() directly in your code
Replace as_matrix() with Pandas’ official replacement: to_numpy(). Here’s how to adjust your conversion code:
# Old code that triggers the error h2o_frame = h2o.H2OFrame(df.as_matrix()) # Fixed code using to_numpy() h2o_frame = h2o.H2OFrame(df.to_numpy())
Even better—you don’t even need to convert to a numpy array manually! H2O can handle Pandas DataFrames directly:
# Even simpler: pass the DataFrame directly h2o_frame = h2o.H2OFrame(df)
2. If the error comes from H2O’s internal code
If you didn’t write as_matrix() yourself, your H2O version is too old to work with modern Pandas. Here’s how to fix this:
- Upgrade H2O to the latest stable version (this is the recommended long-term fix). Use pip or conda to update:
After upgrading, restart your Python session to ensure the new version loads properly.# Using pip pip install --upgrade h2o # Using conda conda update h2o - Temporary fix: Downgrade Pandas (only if upgrading H2O isn’t an option). Install a Pandas version that still supports
as_matrix()(e.g., 0.25.x):pip install pandas==0.25.3
Quick check to verify
After making changes, run a quick test to confirm the conversion works:
import pandas as pd import h2o # Initialize H2O h2o.init() # Create a sample DataFrame df = pd.DataFrame({"col1": [1,2,3], "col2": [4,5,6]}) # Convert to H2OFrame h2o_df = h2o.H2OFrame(df) print(h2o_df)
内容的提问来源于stack exchange,提问作者Divyansh Sharma

