2017-02-16 23 views
2

我已經寫了一個簡短的函數來輸出數據框中每列的最大值(或字符串,最大長度),並對各種數據類型進行了調整。Pandas使用None值的對象類型的最大長度

def maxDFVals(df): 
    for c in df: 
     if str(df[c].dtype) in ('datetime64[ns]'): 
      print('Max datetime of column {}: {}\n'.format(c, df[c].max())) 
     elif str(df[c].dtype) in ('object', 'string_', 'unicode_'): 
      df[c].fillna(value='', inplace=True) 
      print('Max length of column {}: {}\n'.format(c, df[c].map(len).max())) 
     elif str(df[c].dtype) in ('int64', 'float64'): 
      print('Max value of column {}: {}\n'.format(c, df[c].max())) 
     else: 
      print('Unknown data type for column {}!\n'.format(c)) 

它工作正常,但我只是想檢查是否有更好的選擇,以6號線使用fillna,這是我需要的,以便應對無值。理想情況下,我會忽略None,但我無法找到使用skipna = True之類的方法。

如果我真的想我想我能第7行返回無值之後添加

  df[c].replace([''], [None], inplace=True) 

,但這是幾乎沒什麼人會叫Python的...

有沒有人有什麼更好的建議?

+1

不能你試試這個df,可以[C] .dropna()圖(LEN)的.max() –

+0

輝煌,非常感謝@RakeshKumar –

回答

1

試試這個: - 。

def maxDFVals(df): 
    for c in df: 
     if str(df[c].dtype) in ('datetime64[ns]'): 
      print('Max datetime of column {}: {}\n'.format(c, df[c].max())) 
     elif str(df[c].dtype) in ('object', 'string_', 'unicode_'): 
      print('Max length of column {}: {}\n'.format(c, df[c].dropna().map(len).max())) 
     elif str(df[c].dtype) in ('int64', 'float64'): 
      print('Max value of column {}: {}\n'.format(c, df[c].max())) 
     else: 
      print('Unknown data type for column {}!\n'.format(c)) 
+0

是這個工作的對待。之前使用過dropna,但它完全滑落了我的想法。非常感謝。 –