python - '>' not supported between instances of ' str' 和 'int' pandas 函数用于获取阈值

标签 python pandas list function tuples

我有一个df

import pandas as pd
df= pd.DataFrame({'ID': [1,2,3], 
                  
                           'Text':['This num dogs and cats is (111)888-8780 and other',
                              'dont block cow 23 here',
                              'cat two num: dog  and cows here'], 
                                   
                                  'Match':[[('cats', 86), ('dogs', 86), ('dogs', 29)],
                                   [('cow', 33), ('dont', 57), ('cow', 100)], 
                                             [('cat', 100), ('dog', 100), ('cows', 86)] ]
                      })

看起来像这样

    ID                       Text                                   Match
0   1   This num dogs and cats is (111)888-8780 and other   [(cats, 86), (dogs, 86), (dogs, 29)]
1   2   dont block cow 23 here                              [(cow, 33), (dont, 57), (cow, 100)]
2   3   cat two num: dog and cows here                      [(cat, 100), (dog, 100), (cows, 86)]

我的目标是创建一个函数,仅保留 Match 列中高于特定阈值(例如 80)的某些项目,因此我尝试了以下操作

def threshold(column):
    
    column_tup = column
    
    keep_tuple = []
    
    for col in column_tup:
        if column_tup > 80:
            keep_tuple.append()
    
    return pd.Series([keep_tuple], index = ['Keep_Words'])

df_thresh = df.join(df.apply(lambda x: threshold(x),  axis = 1))

但这给了我一个错误

'>' not supported between instances of 'str' and 'int'

我的目标是获得一个带有新列 Keep_Words 的 df,如下所示,其中只有 85 以上的分数才会保存在 Keep_Words

     ID    Text    Match   Keep_Words
0   1      data    data   [(cats, 86), (dogs, 86)]              
1   2      data    data   [(cow, 100)]
2   3      data    data   [(cat, 100), (dog, 100)]

如何更改代码以实现我的目标?

最佳答案

由于您尝试仅更改 Match 列,因此您不妨只将该列传递给 apply:

df.Match.apply(threshold)

我们不再使用 axis 参数,因为我们正在应用它是一个系列,而且它只有一个轴。

然后,每次调用函数时,都会传递一行 df.Match 并将其分配给函数参数,因此我们可以将函数签名重命名为:

def threshold(match_row):

为了可读性。

因此,match_row 将是一个列表,例如,在第一回合中它将是 [(cats, 86), (dogs, 86), (dogs, 29)] 。我们可以像您一样进行迭代,但使用 2 个 for 循环变量:

for name, val in match_row:

这样 name 将成为每个元组的第一个条目,val 是第二个条目。现在我们可以进行过滤:

keep_tuple = []
for name, val in match_row:
    if val > 85:
        keep_tuple.append((name, val))

这很好,但不太Pythonic,因为有列表推导式:

keep_tuple = [(name, val) for name, val in match_row if val > 85]

最后我们可以像您一样返回它:

return pd.Series([keep_tuple], index=["Keep_Words"])

至于调用和赋值,我们可以像您一样加入:

df_thresh = df.join(df.Match.apply(threshold))

总而言之,

def threshold(match_row):
    keep_tuple = [(name, val) for name, val in match_row if val > 85]
    return pd.Series([keep_tuple], index=["Keep_Words"])

df_thresh = df.join(df.Match.apply(threshold))

这给出了

>>> df_thresh

   ID                                               Text                                 Match                            Keep_Words
0   1  This num dogs and cats is (111)888-8780 and other  [(cats, 86), (dogs, 86), (dogs, 29)]              [(cats, 86), (dogs, 86)]
1   2                             dont block cow 23 here   [(cow, 33), (dont, 57), (cow, 100)]                          [(cow, 100)]
2   3                    cat two num: dog  and cows here  [(cat, 100), (dog, 100), (cows, 86)]  [(cat, 100), (dog, 100), (cows, 86)]

最后,对于您遇到的错误:我没有收到该错误,而是收到了臭名昭著的错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

错误,这是因为这一行

if column_tup > 80:

其中column_tup是作为pd.Series的整行,但它在 bool 上下文中的行为是不明确的。

关于python - '>' not supported between instances of ' str' 和 'int' pandas 函数用于获取阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68125847/

相关文章:

python - 测试类的 PEP8 命名约定

python - Pandas:列对象不可调用

python - 线性回归中误差函数的 3D 图

python - 如何以指定的间隔将项目插入列表以匹配另一个列表的len?

python - 将列表移动到 csv 的更好方法?

javascript - Node js中的JSON错误未定义为发布数据的前缀

python - 无法停止项目源代码中的循环

python - 从数据框列中选择非无值

python - 在 matplotlib 中绘制 10 负幂的 xscale

c# - 序列化 List<T> 的 XmlSerializer 的构造函数在与 XmlAttributeOverrides 一起使用时抛出 InvalidOperationException