Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 从字符串中提取第一个和最后一个单词,作为pandas中的新列_Python_String_Pandas_Dataframe - Fatal编程技术网

Python 从字符串中提取第一个和最后一个单词,作为pandas中的新列

Python 从字符串中提取第一个和最后一个单词,作为pandas中的新列,python,string,pandas,dataframe,Python,String,Pandas,Dataframe,我正在努力根据另一列中的字符串创建两个新列 我所拥有的 Profile 0 Technician 1 Service Engineer 2 Sales and Service Support Engineer 我喜欢吃什么 First Last 0 Technician NaN 1 Service Engineer 2 Sales Engineer

我正在努力根据另一列中的字符串创建两个新列

我所拥有的

     Profile
0    Technician
1    Service Engineer
2    Sales and Service Support Engineer
我喜欢吃什么

     First              Last
0    Technician         NaN
1    Service            Engineer
2    Sales              Engineer
我的尝试是使用类似的解决方案

new = tl['Profile'].str.split(' ')
tl['First'] = new[0]
tl['Last'] = new[1]
但这仅适用于第一种情况。

让我们在这里尝试str.extract:


没有regex,使用循环

k=[] 对于df_names_测试中的i['Name']: h=列尼分裂 j=i.split[h-1] k、 附录 df_name_test[Last]=k 直呼其名

k=[] 对于df_names_测试中的i['Name']: j=i.split[0] k、 附录 df_name_test[第一]=k 使用Lambda函数: 名字

df_names_test['First']=df_names_test['Name'].applylambda x:x.split[0] 姓氏:

df_names_test['Last']=df_names_test['Name'].applylambda x:x.split[-1]
df['Profile'].str.extract(r'^(?P<First>\S+).*?(?P<Last>\S+)?$')

        First      Last
0  Technician       NaN
1     Service  Engineer
2       Sales  Engineer
u = df['Profile'].str.partition()
pd.DataFrame({'First': u[0], 'Last': u[2].str.split().str[-1]})

        First      Last
0  Technician       NaN
1     Service  Engineer
2       Sales  Engineer