绘制DataFrame缺失值占比报错:sort_values缺少必填参数'by'
The error you're hitting comes down to one key detail: fs.missing_stats is a DataFrame (not a Series), and pandas' sort_values() method for DataFrames requires you to specify which column to sort by using the by parameter. Your code was missing this critical argument.
Step 1: Fix the sort_values() call
Since you want to sort by the missing_fraction column, update the line where you create prod_count to include the by parameter:
prod_count = pd.DataFrame(fs.missing_stats.sort_values(by='missing_fraction', ascending=False).head(20))
Step 2: Use your sorted top 20 data in the plot
Right now, your barplot uses the original unsorted fs.missing_stats instead of the filtered prod_count you created. To plot only the top 20 features with the highest missing values, adjust the seaborn line to reference prod_count:
sns.barplot(x=prod_count.index, y=prod_count['missing_fraction'].values, alpha=0.8)
Full Corrected Code
Here's the complete, working version with a few optional improvements for readability:
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # Sort and isolate top 20 features with missing values prod_count = pd.DataFrame(fs.missing_stats.sort_values(by='missing_fraction', ascending=False).head(20)) plt.figure(figsize=(10, 6)) # Optional: Resize plot to fit rotated labels sns.barplot(x=prod_count.index, y=prod_count['missing_fraction'].values, alpha=0.8) plt.title('Top 20 Features with Highest Missing Values') plt.ylabel('Missing Fraction', fontsize=12) plt.xlabel('Features', fontsize=12) plt.xticks(rotation=90) plt.tight_layout() # Optional: Prevent label cutoff plt.show()
Debugging Tip for Future Issues
To quickly check if your object is a DataFrame or Series (which affects available methods), run:
print(type(fs.missing_stats)) # Or get a detailed overview: fs.missing_stats.info()
This will help you know exactly what parameters your methods need.
内容的提问来源于stack exchange,提问作者ASH

