首页 > 解决方案 > 删除所有满足正则表达式条件的行

问题描述

试图自学熊猫..并玩弄不同的dtypes

我有一个df如下

df = pd.DataFrame({'ID':[0,2,"bike","cake"], 'Course':['Test','Math','Store','History'] })
print(df)
    ID  Course
0   0   Test
1   2   Math
2   bike    Store
3   cake    History

ID 的 dtype 当然是一个对象。如果 ID 中有一个字符串,我想要做的是删除 DF 中的任何行。

我以为这很简单..

df.ID.filter(regex='[\w]*')

但这会返回所有内容,是否有可靠的方法来处理此类事情?

标签: pythonregexpandas

解决方案


你可以使用to_numeric

df[pd.to_numeric(df.ID,errors='coerce').notnull()]
Out[450]: 
  Course ID
0   Test  0
1   Math  2

推荐阅读