【问题标题】:Extracting only numbers from series Python [duplicate]仅从 Python 系列中提取数字 [重复]
【发布时间】:2021-08-21 04:05:30
【问题描述】:

我有一个看起来像这样的系列:

ID
WTG-1
11
11-1
12B1
13-1
5
6
G7
.
.

我只是希望能够从每个ID 中提取所有个数字。

当我使用我的代码时:

df['ID'] = df['ID'].str.extract('(\d+)', expand=True)

它确实从行的前面提取所有内容,但如果存在字符串/字母/字符分隔符,则会跳过一个数字 - 即对于11-1,它只收集 11 而没有额外的 1。

我希望输出是:

ID         ID #
WTG-1      1
11         11
11-1       111
12B1       121
13-1       131
5          5
6          6
G7         7
.
.

有没有办法计算中间的字符?

【问题讨论】:

  • 我会建议添加熊猫标签

标签: python regex string pandas dataframe


【解决方案1】:

使用findall

df.ID.str.findall('(\d+)').apply(''.join)
Out[92]: 
0      1
1     11
2    111
3    121
4    131
5      5
6      6
7      7
Name: ID, dtype: object

【讨论】:

  • 我怀疑这比我的答案运行得更快
  • @CharlesLandau 在测试之前很难说 :-)
  • 另一个相关的问题 - 对字母执行此操作的方法是 .str.findall('([a-zA-Z ]+)').apply(''.join) 吗?
  • @HelloToEarth 是的
【解决方案2】:

astypeapply 可以做到。

df["ID"] = df["ID"].apply(lambda x: "".join(c for c in x if c.isdigit()).astype(int)

【讨论】:

    【解决方案3】:

    或者替换,

    df['New_ID'] = df.ID.str.replace('\D+', '')
    
        ID      New_ID
    0   WTG-1   1
    1   11      11
    2   11-1    111
    3   12B1    121
    4   13-1    131
    5   5       5
    6   6       6
    7   G7      7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2017-03-13
      • 1970-01-01
      相关资源
      最近更新 更多