gpt4 book ai didi

python 将 split 和 join 组合成 1 行代码

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:42 26 4
gpt4 key购买 nike

我正在尝试将 split 和 join 合并到代码行中,其中 split 仅采用列中分隔的前 3 个单词。

df['c'] = df[['a']].apply(lambda x: x.str.split().str[:3])
df['c'] = df['c'].apply(lambda x: ', '.join(x))

我试过了

df['c'] = df[['a']].apply(lambda x: ', '.join((x.str.split().str[:3])))
but keep getting an error.

最佳答案

Series 移除 str[],因此 apply 使用标量:

df['c'] = df['a'].apply(lambda x: ', '.join((x.split()[:3])))

列表理解备选方案:

df['c'] = [', '.join((x.split()[:3])) for x in df['a']]

关于python 将 split 和 join 组合成 1 行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com