[英]Can you add a condition into a lambda function?
I have the following code:我有以下代码:
clean_tweets['tweet'] = clean_tweets['tweet'].apply(lambda x: remove_noise(x))
I want to add the logic add the condition that remove_noise is done only if the tweet is string我想添加逻辑添加仅当推文为字符串时才执行 remove_noise 的条件
Is it possible to achieve this, are there any alternative ways of getting this done?是否有可能实现这一目标,有没有其他方法可以做到这一点?
Yes, you can use a so-called ternary expression in Python, such as:是的,可以在Python中使用所谓的三元表达式,比如:
(result_if_clause_is_true) if (clause) else (result_if_clause_is_false)
In your specific case:在您的具体情况下:
lambda x: remove_noise(x) if isinstance(x, str) else x
Anything more complex than an if/else operation should become its own function, however.然而,任何比 if/else 操作更复杂的东西都应该成为它自己的 function。
Note that this expression can be used in many other places, not only in lambdas:请注意,此表达式可以在许多其他地方使用,不仅在 lambda 中:
x = y**2 if y < 10 else y/2 # assignment
lambda x: remove_noise(x)
is just remove_noise
lambda x: remove_noise(x)
只是remove_noise
You should probably add the logic into remove_noise
function:您可能应该将逻辑添加到remove_noise
function 中:
def remove_noise(x): if not isinstance(x, str): return x # or None or whatever other value # handle the case where x is a string
As a whole:整体而言:
def remove_noise(x):
if not isinstance(x, str):
return x # or None or whatever othe value
# handle the case where x is a string
clean_tweets['tweet'] = clean_tweets['tweet'].apply(remove_noise)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.