[英]Pandas groupby - dataframe's column disappearing
我有以下名為“new_df”的數據框:
dato uttak annlegg Merd ID Leng BW CF F B H K
0 2020-12-15 12_20 LL 3 1 48.0 1200 1.085069 0.0 2.0 0.0 NaN
1 2020-12-15 12_20 LL 3 2 43.0 830 1.043933 0.0 1.0 0.0 NaN
列是:
'dato', 'uttak', 'annlegg', 'Merd', 'ID', 'Leng', 'BW', 'CF', 'F', 'B', 'H', 'K'
當我做:
new_df.groupby(['annlegg','Merd'],as_index=False).mean()
除了像這樣的“BW”列之外,我得到了所有的手段:
annlegg Merd ID Leng CF F B H K
0 KH 1 42.557143 56.398649 1.265812 0.071770 1.010638 0.600000 0.127907
1 KH 2 42.683794 56.492228 1.270522 0.021978 0.739130 0.230769 0.075862
2 KH 3 42.177866 35.490119 1.125416 0.000000 0.384146 0.333333 0.034483
當我分組時,列“BW”剛剛消失,無論“as_index”是真還是假,這是為什么呢?
看起來內容為BW
列沒有數字類型,而是object
類型,例如用於存儲字符串。 因此,當應用 groupby 和mean
聚合 function 時,游覽列消失了計算 object 的平均值(認為字符串通常沒有意義)。
您應該首先轉換您的BW
列:
第一種方法將安全地將所有列轉換為float
對象。
new_df['BW'] = pd.to_numeric(new_df['BW'])
如果您不想將數據轉換為float
(例如,您知道該列僅包含 int,或者您對浮點精度不感興趣),您可以使用astype
方法,該方法允許您轉換為幾乎任何類型你要:
new_df['BW'] = new_df['BW'].astype(float) # Converts to float
new_df['BW'] = new_df['BW'].astype(int) # Converts to integer
您最終可以像以前一樣應用您的 groupby 和聚合!
這可能是由於錯誤的數據類型。 你可以試試這個。
new_df = new_df.convert_dtypes()
new_df.groupby(['annlegg','Merd'],as_index=False).mean()
您可以通過以下方式檢查 dtype:
new_df.dtype
您可以 try.agg() function 來定位特定列。
new_df.groupby(['annlegg','Merd']).agg({'BW':'mean'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.