How to get maximum length of each column in the data frame using pandas python
One solution is to use numpy.vectorize
. This may be more efficient than pandas
-based solutions.
You can use pd.DataFrame.select_dtypes
to select object
columns.
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': ['abc', 'de', 'abcd'],
'B': ['a', 'abcde', 'abc'],
'C': [1, 2.5, 1.5]})
measurer = np.vectorize(len)
Max length for all columns
res1 = measurer(df.values.astype(str)).max(axis=0)
array([4, 5, 3])
Max length for object columns
res2 = measurer(df.select_dtypes(include=[object]).values.astype(str)).max(axis=0)
array([4, 5])
Or if you need output as a dictionary:
res1 = dict(zip(df, measurer(df.values.astype(str)).max(axis=0)))
{'A': 4, 'B': 5, 'C': 3}
df_object = df.select_dtypes(include=[object])
res2 = dict(zip(df_object, measurer(df_object.values.astype(str)).max(axis=0)))
{'A': 4, 'B': 5}
Some great answers here and I would like to contribute mine
Solution:
dict([(v, df[v].apply(lambda r: len(str(r)) if r!=None else 0).max())for v in df.columns.values])
Explanation:
#convert tuple to dictionary
dict(
[
#create a tuple such that (column name, max length of values in column)
(v, df[v].apply(lambda r: len(str(r)) if r!=None else 0).max())
for v in df.columns.values #iterates over all column values
])
Sample output
{'name': 4, 'DoB': 10, 'Address': 2, 'comment1': 21, 'comment2': 17}
You can use min max after using str and len method
df["A"].str.len().max()
df["A"].str.len().min()
df["Column Name"].str.len().max()
df["Column Name"].str.len().min()