【问题标题】:How to replace row value with only the integers within the value using Pandas? [duplicate]如何使用 Pandas 仅用值中的整数替换行值? [复制]
【发布时间】:2020-12-14 04:12:25
【问题描述】:

我有一堆这样的专栏

District
________
State District 1
State District 2
State District 3
4th State House District
5th State House District
State District 6
...
State District 17

我想转换其中的每一个,使其只包含整数值:

District
________
1
2
3
4
5
6
...
17

如何使用 Pandas 实现这一点?这对 Pandas 是否可行,还是我必须使用 SQL 或某些数据库语言执行此转换?

【问题讨论】:

  • Likey 一个正则表达式解决方案:df.District.str.extract(r"(\d+)")

标签: python sql pandas postgresql dataframe


【解决方案1】:

使用str.replace 的简单解决方案是去掉所有非数字字符:

df['District'] = df['District'].str.replace('\D', '')

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2020-12-24
    • 2020-01-12
    • 2022-07-08
    • 1970-01-01
    • 2021-04-14
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多