如何基于含缺失值的Pandas DataFrame创建新数据表?
Hey there! Looking at your sample DataFrame with those NaN values, I’m guessing you want to create a new DataFrame by handling those missing entries in some way. Let’s walk through a few common use cases that might match what you’re after:
If you want to replace NaNs with specific values or calculated metrics, here are a few practical options:
Fill with a constant value (e.g., 0)
df_filled_zero = df.fillna(0)
Result:
Col_A Col_B Col_C2 0.001 0.00 0.4566
3 0.250 0.46 0.0000
4 1.000 0.00 2.0000
5 0.000 0.00 5.5000
Fill with column means (for numeric columns)
df_filled_mean = df.fillna(df.mean(numeric_only=True))
Result:
Col_A Col_B Col_C2 0.001 0.46 0.4566
3 0.250 0.46 2.6589
4 1.000 0.46 2.0000
5 0.417 0.46 5.5000
Forward-fill (use the previous row's value)
df_filled_ffill = df.fillna(method='ffill')
Result:
Col_A Col_B Col_C2 0.001 NaN 0.4566
3 0.250 0.46 0.4566
4 1.000 0.46 2.0000
5 1.000 0.46 5.5000
If you want to filter out rows or columns that have any NaNs:
Drop rows with any missing values
df_clean_rows = df.dropna(axis=0)
Note: Since every row in your sample has at least one NaN, this will return an empty DataFrame.
Drop columns with any missing values
df_clean_cols = df.dropna(axis=1)
Note: Similarly, every column in your sample has NaNs, so this will also return an empty DataFrame.
If you want a boolean DataFrame that marks where NaNs are located:
df_missing_flags = df.isna()
Result:
Col_A Col_B Col_C
2 False True False
3 False False True
4 False True False
5 True True False
If you had a specific transformation in mind (like calculating a new column based on existing ones, or reshaping the data), feel free to share more details!
内容的提问来源于stack exchange,提问作者Kdog

