在 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])
我有一个包含 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])