我有一个pandas数据帧,df [lists]包含整数和字符串,它具有以下格式:
0 [(a,b,89), (a,y,992), (a,t, 99), (a,m, 1028)]
1 [(b,u,855), (b,tt,934), (b, g, 69)]
2 [(c,k, 546),(c,gf,134), (c, dd, 569)]
3 [(d,zv, 546),(d,gyr,8834), (d, dds, 5693), (d, ddd, 3459)]
实际上字符a,b,tt等更长并使用计算汉明距离 我想得到的是每行中的最大值,并将其写为df [max]:
0 [1028]
1 [934]
2 [569]
3 [8834]
我来这里使用:
combined = ((x, y, (5x - 3y) for x, y in combinations(df['elements'], if x != y)
series = Series(list(g) for k, g in groupby(combined, key=itemgetter(0)))
series = df[lists]
当我使用时:
from operator import itemgetter
df['lst'].apply(lambda x: [max(x, key=itemgetter(2))[-1]])
我收到以下错误:
Traceback (most recent call last):
File "C:\Users\Desktop\phash\dene_2.py", line 78, in <module>
df['similarity'].apply(lambda x: [max(x, key=itemgetter(2))[-1]])
File "C:\Users\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\series.py", line 2294, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1207, in pandas.lib.map_infer (pandas\lib.c:66124)
File "C:\Users\Desktop\phash\dene_2.py", line 78, in <lambda>
df['similarity'].apply(lambda x: [max(x, key=itemgetter(2))[-1]])
TypeError: 'float' object is not iterable
答案 0 :(得分:1)
您最好的选择是使用不那么快的apply
变体。假设包含list
单元格的列名称由"lst"
表示,您可以获取元组列表中存在的每个第三个元素,并通过比较它们来查找最大值。然后从计算出的tuple
中选择它的最后一个元素并将其转换为单个项list
:
from operator import itemgetter
df['lst'].apply(lambda t: [max(t, key=itemgetter(2))[-1]])
0 [1028]
1 [934]
2 [569]
3 [8834]
Name: lst, dtype: object
使用的数据:
df = pd.DataFrame(dict(lst=[[('a','b', 89), ('a','y', 992), ('a','t', 99), ('a','m', 1028)],
[('b','u', 855), ('b','tt', 934), ('b', 'g', 69)],
[('c','k', 546),('c','gf', 134), ('c', 'dd', 569)],
[('d','zv', 546),('d','gyr', 8834), ('d', 'dds', 5693), ('d', 'ddd', 3459)]]))
<强> 编辑: 强>
由于存在可能存在被映射为float
个对象的缺失值的可能性,您可以根据它们的类型过滤单元格并对它们执行迭代并保持其他单元格保持不变:
df['lst'].apply(lambda t: [max(t, key=itemgetter(2))[-1] if isinstance(t, list) else t])