【问题标题】:Get specific characters from string in DataFrame从 DataFrame 中的字符串中获取特定字符
【发布时间】:2014-10-30 17:22:51
【问题描述】:

我有一个来自我读入的 Excel 文件的 Pandas DataFrame。我在数据框中有一个特定的列,其中包含以下任何形式的字符串:

22th/Dec if we receive order by 26/Sep
12th/Dec if we receive order by 26/Sep
10th/November if we receive order by 26th/Sep

我希望获取数字日期编号(例如 22 或 12 或 10)和字符串月份名称(例如 12 月或 11 月),因此我想创建一个仅获取日期编号的变量另一个抓取月份名称。

我可以使用像here 这样的一系列左/右​​,但这并不是那么简单。有时数据在开头可能是“第 9 个”或“第 8 个”,因此我放置的字符数在那里不起作用,除非我执行某种“如果长度 > x,则”代码。将特定字符抓取到新变量中的最简洁方法是什么?

【问题讨论】:

    标签: python string pandas text-extraction


    【解决方案1】:

    DataFrame str.extract 方法采用正则表达式,这正是你想要的。

    df['text_col'].str.extract(r'^(\d+)\S*/(\S+) ')
    

    这将返回一个包含两列数据的 Dataframe。

    或者为了获得更好的标题,

    >>> df['text_col'].str.extract(r'^(?P<day>\d+)\S*/(?P<month>\S+) ')
      day     month
    0  22       Dec
    1  12       Dec
    2  10  November
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多