具有不同类型对象的数据帧-python
我需要将列数据帧的数值转换为float,但它们是字符串格式的具有不同类型对象的数据帧-python,python,pandas,formatting,Python,Pandas,Formatting,我需要将列数据帧的数值转换为float,但它们是字符串格式的 d = {'col1': ['1', '2.1', '3.1'], 'col2': ['yes', '4', '6'], 'col3': ['1', '4', 'not']} 预期: {'col1': [1, 2.1, 3.1], 'col2': ['yes', 4, 6], 'col3': [1, 4, 'not']} 这是可能的,但不建议这样做,因为如果列中存在混合值,则某些函数将失败: d = {'
d = {'col1': ['1', '2.1', '3.1'],
'col2': ['yes', '4', '6'],
'col3': ['1', '4', 'not']}
预期:
{'col1': [1, 2.1, 3.1],
'col2': ['yes', 4, 6],
'col3': [1, 4, 'not']}
这是可能的,但不建议这样做,因为如果列中存在混合值,则某些函数将失败:
d = {'col1': ['1', '2.1', '3.1'],
'col2': ['yes', '4', '6'],
'col3': ['1', '4', 'not']}
df = pd.DataFrame(d)
def func(x):
try:
return float(x)
except Exception:
return x
df = df.applymap(func)
print (df)
col1 col2 col3
0 1.0 yes 1
1 2.1 4 4
2 3.1 6 not
print (df.to_dict('l'))
{'col1': [1.0, 2.1, 3.1], 'col2': ['yes', 4.0, 6.0], 'col3': [1.0, 4.0, 'not']}
另一个解决方案:
df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).fillna(df)
可能重复的