2017-02-16 4 views
2

データフレームの各列の最大値(または文字列、最大長)を出力するための短い関数を作成しました。オブジェクトタイプの最大長なし値なし

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)) 

それは正常に動作しますが、私はちょうど私がなし値に対処するために必要なfillnaを使用して、6行目のより良い代替手段があるかどうかを確認したかったです。理想的には、私はNoneを無視するだけですが、skipna = Trueのようなものを使う方法は見つけられませんでした。

私は本当に誰もが任意のより良い提案を持っています私はなし値を返すために7行目の後に

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

を追加することができると思いますが、それは誰もがPython的に呼ぶものはほとんどありません...

したい場合?

+1

あなたは、これは[C] .dropna()dfを試すことができないマップを(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

はい、この作品治療する。前にドロップnaを使ったことがありましたが、それは私の心を完全に滑らせました。どうもありがとう。 –

関連する問題