Python新手跟随教程操作时遇DataFrame无to_frame属性报错求助
Hey there! Let's work through this error step by step.
First, let's recap your code logic for calculating missing value ratios:
miss = train.isnull().sum()/len(train) miss = miss[miss>0] miss.sort_values(inplace = True)
This code should return a pandas Series (not a DataFrame) where each index is a column name from your train DataFrame, and the values are the corresponding missing value ratios.
The error 'DataFrame' object has no attribute 'to_frame' tells us that when you tried calling .to_frame(), you were actually calling it on a DataFrame instead of the miss Series you intended. Here are the most likely reasons and fixes:
1. You accidentally overwrote the miss variable
Check if you have any code after the three lines above that reassigns miss to a DataFrame. For example, something like:
# This would turn miss into a DataFrame and overwrite your original Series miss = train[['Electrical', 'MasVnrType']]
If that's the case, rename your DataFrame variable to something else (like selected_cols) to keep the original miss Series intact.
2. You called .to_frame() on the wrong variable
Double-check that you're running miss.to_frame() and not train.to_frame() (or another DataFrame variable). to_frame() is a method exclusive to pandas Series, which is why calling it on a DataFrame throws an error.
3. Verify the type of miss
To confirm what type of object miss is, add this line right before you call .to_frame():
print(type(miss))
- If it outputs
<class 'pandas.core.series.Series'>, thenmiss.to_frame()will work perfectly. You can even specify a column name for the resulting DataFrame:miss_df = miss.to_frame(name='missing_ratio') - If it outputs
<class 'pandas.core.frame.DataFrame'>, you'll need to trace back your code to find wheremissgot converted to a DataFrame.
As a side note, since you're working on a machine learning project, once you have your missing value ratios in a DataFrame, you can easily visualize them with:
miss_df.plot(kind='barh', figsize=(10,6))
内容的提问来源于stack exchange,提问作者Serdia

