I have a dataframe with the column as follows;
JavaScript
x
6
1
ID, Quantity
2
1 1,000 total
3
2 802 destroyed
4
3 >689 total
5
4 1,234-1,900 lost
6
I want the output as follows:
JavaScript
1
6
1
ID, Quantity
2
1 1,000
3
2 802
4
3 689
5
4 1234-1,900
6
I have tried,
JavaScript
1
2
1
df['Quantity'] = df['Quantity'].str.replace(r' s', '')
2
No success so far.
Advertisement
Answer
This depends on what possible values can be in the quantity column. If there can never be a space in the numerical part (as in your example) you can use Series.str.partition
:
JavaScript
1
5
1
number_column, space_column, text_column = df['Quantity'].str.partition()
2
del space_column # These two lines are not required but I like to include them
3
del text_column # to improve code readability and keep pylint happy
4
df['Quatity'] = number_column
5
This can also be written in one line:
JavaScript
1
2
1
df['Quantity'] = df['Quantity'].str.partition()[0]
2