亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Pandas 數據框列表列中查找最大值

在 Pandas 數據框列表列中查找最大值

阿晨1998 2024-01-24 16:15:48
我有一個數據框(df):df = pd.DataFrame({'A' : [54321, 'it is 54322', 'is it 54323 or 4?', np.NaN]})我可以找到其中的數字:df['B'] = df.A.replace(regex={'[^\w]':'','^\D+':'','\D+':' '}).str.split('\s')                   A           B0              54321         NaN1        it is 54322     [54322]2  is it 54323 or 4?  [54323, 4]3                NaN         NaN但是當我嘗試找到每行的最大數字時:df['C'] = df['B'].apply(lambda x : max(x))我得到:TypeError: 'float' object is not iterable
查看完整描述

2 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

將 lambda 函數與 一起使用if-else,還添加了轉換為整數以確保正確max:


f = lambda x : max(int(y) for y in x) if isinstance(x, list) else np.nan

df['C'] = df['B'].apply(f)

print (df)

? ? ? ? ? ? ? ? ? ?A? ? ? ? ? ?B? ? ? ? C

0? ? ? ? ? ? ? 54321? ? ? ? ?NaN? ? ? NaN

1? ? ? ? it is 54322? ? ?[54322]? 54322.0

2? is it 54323 or 4?? [54323, 4]? 54323.0

3? ? ? ? ? ? ? ? NaN? ? ? ? ?NaN? ? ? NaN

或者使用Series.str.extractallforMultiIndex與 Convert toint并使用max每個第一級:

df = pd.DataFrame({'A' : [54321, 'it is 54322', 'is it 54323 or 4?', np.NaN]})

df['C'] = df.A.astype(str).str.extractall('(\d+)').astype(int).max(level=0)

print (df)

? ? ? ? ? ? ? ? ? ?A? ? ? ? C

0? ? ? ? ? ? ? 54321? 54321.0

1? ? ? ? it is 54322? 54322.0

2? is it 54323 or 4?? 54323.0

3? ? ? ? ? ? ? ? NaN? ? ? NaN


查看完整回答
反對 回復 2024-01-24
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

另一個解決方案:


import re

df['B'] = df['A'].apply(lambda x: pd.Series(re.findall(r'\d+', str(x))).astype(float).max())

print(df)

印刷:


                   A        B

0              54321  54321.0

1        it is 54322  54322.0

2  is it 54323 or 4?  54323.0

3                NaN      NaN


查看完整回答
反對 回復 2024-01-24
  • 2 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號