簡體   English   中英

數據框中列表中的最長字符串

[英]Longest Strings in List in Dataframe

我想返回數據框中列表中最長的字符串。 原始數據將如下所示:

items
['pants','hat']
['clothes']
['mouse']

我想要的輸出是:

items               longest_str
['pants','hat']     ['pants']
['clothes']         ['clothes']
['mouse','xx']      ['mouse']

我的代碼是:

def longest(i):
    return max(i,key=len)

for i in range(0:2):
    print(df['items'][i])
    print(longest(df['items'][i]))

但它沒有打印出我想要的東西。 我的最終目標是在整個數據框中找到最長的字符串。 請建議任何其他最佳方法來解決它

只需在df.apply調用longest函數:

In [492]: df['longest_str'] = df['items'].apply(lambda x: [longest(x)])

In [493]: df
Out[493]: 
          items longest_str
0  [pants, hat]     [pants]
1     [clothes]   [clothes]
2       [mouse]     [mouse]

嘗試:

df = pd.DataFrame({'items':[['pants', 'hat'],['clothes'],['mouse', 'xx']]})

df['longest_str'] = [[max(x, key=len)] for x in df['items']]

df

輸出:

          items longest_str
0  [pants, hat]     [pants]
1     [clothes]   [clothes]
2   [mouse, xx]     [mouse]

完成你的總問題:

df = pd.DataFrame({'items':[['pants', 'hat'],['clothes'],['mouse', 'xx']]})

df['longest_str'] = [max(x, key=len) for x in df['items']]

max((x for x in df['longest_str']), key=len)

輸出:

'clothes'

變得很可愛:

df['items'].explode().loc[lambda x: x.str.len().max() == x.str.len()].to_numpy()[0]

輸出:

'clothes'

使用apply,也許沒有你的函數會更好。

df['longest_str'] = df['items'].apply(lambda x: max(x, key=len))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM