我有一个数据帧,列如下;
ID, Quantity
1 1,000 total
2 802 destroyed
3 >689 total
4 1,234-1,900 lost
我希望输出如下:
ID, Quantity
1 1,000
2 802
3 689
4 1234-1,900
我试过了,
df['Quantity'] = df['Quantity'].str.replace(r' s', '')
到目前为止没有成功。
这取决于数量列中可能存在的值。如果数字部分永远不会有空格(如您的示例(,您可以使用Series.str.partition
:
number_column, space_column, text_column = df['Quantity'].str.partition()
del space_column # These two lines are not required but I like to include them
del text_column # to improve code readability and keep pylint happy
df['Quatity'] = number_column
这也可以写在一行:
df['Quantity'] = df['Quantity'].str.partition()[0]