首页 > 解决方案 > 如何使用 Pandas 仅用值中的整数替换行值?

问题描述

我有一堆这样的专栏

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 甚至可以实现这一点,还是我必须使用 SQL 或某些数据库语言来执行这种转换?

标签: pythonsqlpandaspostgresqldataframe

解决方案


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

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

推荐阅读