繁体   English   中英

在 lambda 函数中使用列表理解?

[英]Using list comprehension within lambda function?

我有一个包含 n-gram 元组列表的数据框。 我想将元组列表转换为字符串列表。 为此,我试图在我的 lambda 函数中使用列表理解。 但是,我不断收到错误消息,说我的列表未定义。

id     n_grams
 1     [(thanks), (thanks, past), (thanks, past, blue)]
 2     [(support), (support, arm), (support, arm, brace), (support, arm, brace, left)]
 3     [(blue), (blue, sky), (blue, sky, rain)]
 4     [(breaking), (breaking, news), (breaking, news, fire), (breaking, news, fire, aparment)]

我试图得到:

id     n_grams
 1     ["thanks", "thanks past", "thanks past blue"]
 2     ["support", "support arm", "support arm brace", "support arm brace left"]
 3     ["blue", "blue sky", "blue sky rain"]
 4     ["breaking", "breaking news", "breaking news fire", "breaking news fire apartment"]

我试过了:

data['n_grams'] = data.n_grams.apply(lambda row: " ".join(x) for x in row)

但我不断收到错误消息:

NameError: name 'row' is not defined

感谢 rdas 的评论,解决方案只是使用硬括号:

data['n_grams'] = data.n_grams.apply(lambda row: [" ".join(x) for x in row])

这应该工作:

df.n_grams.apply(lambda row: [" ".join(x) for x in row]) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM