Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python将拆分和联接组合成一行代码_Python_String_Pandas_Lambda - Fatal编程技术网

python将拆分和联接组合成一行代码

python将拆分和联接组合成一行代码,python,string,pandas,lambda,Python,String,Pandas,Lambda,我正在尝试将拆分和联接合并到代码行中,其中拆分只取列的前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. 删除系

我正在尝试将拆分和联接合并到代码行中,其中拆分只取列的前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. 

删除
系列的
str
[]
,以便
apply
使用标量:

df['c'] = df['a'].apply(lambda x: ', '.join((x.split()[:3])))
列出备选方案:

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

您可以使用Pandas
str
访问器,也可以使用常规Python
str
方法的列表理解。列表理解通常更有效。您应该将拆分限制为3,以消除不必要的操作

df = pd.DataFrame({'A': ['ab cd ef gh ij', 'kl mn op qr', 'st uv', 'wx yz 123 456']})

df['B'] = df['A'].str.split(n=3).str[:3].str.join(', ')
df['C'] = [', '.join(x.split(maxsplit=3)[:3]) for x in df['A']]

assert df['B'].equals(df['C'])

print(df)

                A            B            C
0  ab cd ef gh ij   ab, cd, ef   ab, cd, ef
1     kl mn op qr   kl, mn, op   kl, mn, op
2           st uv       st, uv       st, uv
3   wx yz 123 456  wx, yz, 123  wx, yz, 123

太棒了,谢谢!我试图提高投票率,但我的代表仍在投票low@SHK-谢谢,在发布问题15分钟后可以:)