报错
FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.
For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.
data['age'].fillna(np.mean(data.age), inplace=True)
我的代码
import numpy as np import pandas as pd # 创建一个包含缺失值的示例数据 data = pd.DataFrame({ 'age': [25, 30, np.nan, 35, np.nan], 'gender': ['M', 'F', 'M', 'F', 'M'] }) print("原始数据:") print(data) # 使用均值填充年龄特征的缺失值 data['age'].fillna(np.mean(data.age), inplace=True) print("\n填充后的数据:") print(data)
修改
import numpy as np
import pandas as pd
# 创建一个包含缺失值的示例数据
data = pd.DataFrame({
'age': [25, 30, np.nan, 35, np.nan],
'gender': ['M', 'F', 'M', 'F', 'M']
})
print("原始数据:")
print(data)
# 使用均值填充年龄特征的缺失值
# data['age'].fillna(np.mean(data.age), inplace=True)
mean_age = np.mean(data['age'])
print(mean_age)
data.fillna({'age': mean_age}, inplace=True)
print("\n填充后的数据:")
print(data)
分析:
上一种写法过时了