【问题标题】:Columns pandas data frame with different type object - python具有不同类型对象的列熊猫数据框 - python
【发布时间】:2019-02-18 21:53:11
【问题描述】:

我需要将列(熊猫数据框)的数值转换为浮点数,但它们是字符串格式。

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']}

【问题讨论】:

标签: python pandas formatting


【解决方案1】:

这是可能的,但不推荐,因为如果列中的混合值,某些函数会失败:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多