如何在Python中删除无法转换为int64类型的DataFrame行?
解决Pandas中无法转换为int64的行删除问题
嘿,这个问题我之前也碰到过!当你的字符串列里混了非数字字符时,直接用astype('int64')肯定会报错。下面给你两个实用的办法来过滤掉那些没法转成int64的行,完美得到你想要的结果:
方法一:用pd.to_numeric强制转换并过滤NaN
这个方法先把无法转换的值变成NaN,再删掉这些行,最后转成int类型:
import pandas as pd test_df = pd.DataFrame({'foo':['1','2','92#']}) # 尝试转换,不能转的会被设为NaN test_df['foo'] = pd.to_numeric(test_df['foo'], errors='coerce') # 删除含NaN的行,再转成int64 result_df = test_df.dropna(subset=['foo']).astype({'foo': 'int64'}) print(result_df)
方法二:用正则表达式直接过滤纯数字行
如果你想先筛选出符合条件的行再转换,正则表达式是个好选择:
import pandas as pd test_df = pd.DataFrame({'foo':['1','2','92#']}) # 只保留全是数字的行,再转类型 result_df = test_df[test_df['foo'].str.match(r'^\d+$')].astype({'foo': 'int64'}) print(result_df)
两种方法运行后都会得到你想要的结果:
foo 0 1 1 2
内容的提问来源于stack exchange,提问作者freefrog
相关产品推荐
相关产品推荐

