Alien13
Alien13

Reputation: 618

Get the value with the greatest length in a one-column dataframe

I was wondering how I can get the value with the greatest length in a one-column dataframe. So far I have only managed to get the numerical length of the longest value. I have really tried but I cannot seem to get the value itself.

df = df.astype('str')
longest_value[i] = df.columns.map(len).max()

Thanks a lot

Upvotes: 1

Views: 88

Answers (1)

cs95
cs95

Reputation: 402814

You'll need str.len + idxmax.

df.iloc[df.iloc[:, 0].str.len().idxmax()]

Or,

df.iat[df.iloc[:, 0].str.len().idxmax(), 0]

I've broken down the steps for a sample DataFrame -

df = pd.DataFrame({'col1': ['aaa', 'bbbbb', 'cccccccc', 'ddd', 'ee', 'fffff']})

df    
       col1
0       aaa
1     bbbbb
2  cccccccc
3       ddd
4        ee
5     fffff

df.iloc[:, 0].str.len()    
0    3
1    5
2    8
3    3
4    2
5    5
Name: col1, dtype: int64

df.iloc[:, 0].str.len().idxmax()
2

df.iloc[df.iloc[:, 0].str.len().idxmax()]    
col1    cccccccc
Name: 2, dtype: object

And,

df.iat[df.iloc[:, 0].str.len().idxmax(), 0]
'cccccccc'

Upvotes: 4

Related Questions