不確定是否符合樓主需求,看看是否合用。
import pandas as pd
import numpy as np
file = 'Fish.csv'
df = pd.read_csv(file)
print(len(df))
print(df.columns)
df.head()
df_mean = df[['Species', 'Length1']].groupby('Species').mean()
df_mean
df_dict = df_mean.squeeze().to_dict()
df_dict
for i in df['Species']:
df.loc[(df['Species']==i) & (df['Length1'].isna()), 'Length1'] = df_dict[i]
df
感謝大大
可是我用了之後,沒有出現結果
後來我是這樣寫,
for i in df['Species']:
df[(df['Species']==i) & (df['Length_cm'].isna())] = df[(df['Species']==i) & (df['Length_cm'].isna())].fillna(df_mean.iloc[i,0])
df[(df['Species']==i) & (df['Weight_g'].isna())] = df[(df['Species']==i) & (df['Weight_g'].isna())].fillna(df_mean.iloc[i,1])
不曉得是不是資料不一樣的關係?也謝謝你的分享。