Reputation: 473
I have strings that will always contain one space, sometimes two and conceivably three. Eg
Run 8890
Test Run GoLive
Test Run Fall Over
I want to delete all data after the last space. I had thought the following would work but it throws an error:
result['t1'] = result['t1'].str.rsplit(' ')[-1]
Can anyone see what I'm doing wrong?
Upvotes: 0
Views: 537
Reputation: 133528
1st solution: With str.extract
function of Pandas you could try following.
df['column'].str.extract(r'(.*)(?=\s+)')
Explanation: using str.extract
function of Pandas and using regex to match everything till last space in value in single capturing group.
2nd solution: With str.replace
function of Pandas try following:
df['column'].str.replace(r'\s+\S+$','')
Explanation: Using str.replace
using regex to replace everything from last space(s) with non-spaces values till end with NULL.
Output will be as follows:
0 Run
1 Test Run
2 Test Run Fall
Upvotes: 1
Reputation: 24314
use:
result['t1']=result['t1'].str.rsplit(' ').str[:-1].apply(' '.join)
Output of result
:
t1
0 Run
1 Test Run
2 Test Run Fall
Upvotes: 2
Reputation: 23217
If you want to delete all data after the last space rather than retain data after the last space, you could use:
result['t1'] = result['t1'].str.rsplit(' ').str[:-1].str.join(' ')
Result:
t1
0 Run
1 Test Run
2 Test Run Fall
Upvotes: 1