我有一个来自 Excel 电子表格的 Pandas 系列,它主要是 float ,但有一些字符串未被解析,因为货币位于不同的区域设置:
s = pd.Series(['1,23', '4.56,78', 1, 2.0, np.nan])
我只想选择那些字符串项目,以便我可以应用转换:
s[s.apply(type) == str] = s[s.apply(type) == str].str.replace('.', '').str.replace(',', '.')
s.astype(float)
0 1.23
1 456.78
2 1.00
3 2.00
4 NaN
dtype: float64
但我找不到一种好的(内置的、矢量化的)方法来逐行获取或选择数据类型。有没有更好的办法?
最佳答案
您可以使用 str.translate
同时做这两件事(转换,改变 dtype):
pd.to_numeric(s.str.translate(str.maketrans({'.': '', ',': '.'}))).fillna(s)
0 1.23
1 456.78
2 1.00
3 2.00
4 NaN
dtype: float64
dtype
将是 'float64'
。
关于python - 从 Pandas 的混合数据类型系列中选择具有给定数据类型的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189685/