忽略pandas数据帧中的非数字字符串值

dev*_*150 7 python pandas

我有一个DataFrame,其中一列可能有三种值,整数(12331),整数作为字符串('345')或其他一些字符串('text').

有没有办法从数据帧中删除包含最后一种字符串的所有行,并将第一种字符串转换为整数?或者至少有一些方法可以忽略导致类型错误的行,如果我正在对列进行求和.

这个数据框来自于读取一个非常大的CSV文件(25 GB),所以我想要一些在读取块时可以使用的解决方案.

Mar*_*ius 9

Pandas有一些工具可以转换这些类型的列,但它们可能并不完全符合您的需求.pd.to_numeric转换像你的混合列,但转换非数字字符串NaN.这意味着您将获得浮点列,而不是整数,因为只有浮点列可以具有NaN值.这通常无关紧要,但要注意这一点很好.

df = pd.DataFrame({'mixed_types': [12331, '345', 'text']})

pd.to_numeric(df['mixed_types'], errors='coerce')
Out[7]: 
0    12331.0
1      345.0
2        NaN
Name: mixed_types, dtype: float64
Run Code Online (Sandbox Code Playgroud)

如果您想删除所有NaN行:

# Replace the column with the converted values
df['mixed_types'] = pd.to_numeric(df['mixed_types'], errors='coerce')

# Drop NA values, listing the converted columns explicitly
#   so NA values in other columns aren't dropped
df.dropna(subset = ['mixed_types'])
Out[11]: 
   mixed_types
0      12331.0
1        345.0
Run Code Online (Sandbox Code Playgroud)