iT邦幫忙

0

pandas處理多種類的空值:要如何依不同種類的身高、體重平均後,分別填入空值呢?

  • 分享至 

  • xImage

依不同種類的身高、體重分別做平均後,有什麼比較好的方法分別填入空值呢?

https://ithelp.ithome.com.tw/upload/images/20220506/20122436NYFCR36LfL.png

fillano iT邦超人 1 級 ‧ 2022-05-06 14:21:59 檢舉
如果同一種類不僅做身高、體重的平均,還算出身高與體重之間的相關係數,那或許有可能從體重推導出合理的身高?看有沒有高手熟悉這方面的...
沒資料就是沒資料(NaN)
硬填一個數字有什麼意義 XD

填了數字之後
這份資料還有什麼參考價值呢
(無法區分那些是原始數字,那些數字是程式「填」回去的)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
mackuo
iT邦研究生 2 級 ‧ 2022-05-07 11:03:57

不確定是否符合樓主需求,看看是否合用。

import pandas as pd
import numpy as np

file = 'Fish.csv'

df = pd.read_csv(file)
print(len(df))
print(df.columns)
df.head()

https://ithelp.ithome.com.tw/upload/images/20220507/2012233593a4W95k4M.png

df_mean = df[['Species', 'Length1']].groupby('Species').mean()
df_mean

https://ithelp.ithome.com.tw/upload/images/20220507/20122335hDc50iwGBL.png

df_dict = df_mean.squeeze().to_dict()
df_dict

https://ithelp.ithome.com.tw/upload/images/20220507/20122335ham8gRmHLx.png

for i in df['Species']:
    df.loc[(df['Species']==i) & (df['Length1'].isna()), 'Length1'] = df_dict[i]

df

https://ithelp.ithome.com.tw/upload/images/20220507/20122335XejBZp0cWT.png

Amold iT邦新手 5 級 ‧ 2022-05-10 13:28:06 檢舉

感謝大大
可是我用了之後,沒有出現結果
https://ithelp.ithome.com.tw/upload/images/20220510/20122436vRtJy1by0M.png

後來我是這樣寫,

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])
mackuo iT邦研究生 2 級 ‧ 2022-05-11 08:37:55 檢舉

不曉得是不是資料不一樣的關係?也謝謝你的分享。

我要發表回答

立即登入回答