我编写了一个简短的函数来输出数据框中每一列的最大值(对于字符串,最大长度),并针对各种数据类型进行了调整。
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 值。理想情况下,我会忽略 None,但我找不到使用类似 skipna=True 的方法。
如果我真的想,我想我可以添加
df[c].replace([''], [None], inplace=True)
在第 7 行之后返回 None 值,但这几乎不是任何人所说的 Pythonic...
有没有人有更好的建议?
最佳答案
试试这个:-
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))
关于python - 具有 None 值的 Pandas 对象类型的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270757/