python - 在列表的 Pandas 数据框列中查找最大值
问题描述
我有一个数据框(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 B
0 54321 NaN
1 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
解决方案
使用 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.extractall
for MultiIndex
with convert to int
and using max
per first level:
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
推荐阅读
- angular - 如何以角度显示过滤的对象列表?
- python - 如何识别字符串的最小形式?
- unity3d - 无法使用“屏幕空间叠加”在画布中获取对象的真实位置
- angular - ASP.Net Core 服务器中的 Angular PWA - Serviceworker-Cache 不起作用
- verilog - verilog/系统verilog中的最大线位宽度是多少
- python - 有哪些方法可以为 Flask 应用程序播种?
- python - 如何删除换行符但在文本文件中保留空白行?
- mysql - 将动态参数传递给 gman_do mysql udf 函数
- apache-nifi - 通过 SplitJson 和 MergeContent 过滤 JSON
- sql - 查找同一列的时间戳差异,但依赖于其他列的事件