【问题标题】:How to remove text and remain with interger values in python dataframe column如何删除文本并在python数据框列中保留整数值
【发布时间】:2020-07-07 07:31:19
【问题描述】:

我有一个列如下的数据框;

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', '')

目前没有成功。

【问题讨论】:

    标签: python string dataframe replace integer


    【解决方案1】:

    这取决于数量列中的可能值。如果数字部分永远不能有空格(如您的示例),您可以使用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]
    

    【讨论】:

      猜你喜欢
      • 2020-02-13
      • 2021-02-19
      • 2021-11-26
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2021-03-27
      • 2021-09-14
      相关资源
      最近更新 更多