2024-09-27 00:17:15 发布
网友
我有一个带有字符串类型列的数据框,其中包含字符和数字条目
下面是一个示例df:
A B 101a5 12222 11111 e2edw2 22222 33333 asxaa 0045
我想将字符串中只有数值的条目转换为整数,但将其余条目保留为字符串
最好的方法是什么
提前谢谢
只需将数据帧转换为整数,并忽略任何会返回原始字符串的错误
再简单不过了
df.astype(int, errors='ignore') # pandas 1.0.0 >>> df.astype(int, errors='ignore').applymap(type) A B 0 <class 'str'> <class 'int'> 1 <class 'int'> <class 'str'> 2 <class 'int'> <class 'int'> 3 <class 'str'> <class 'int'>
您可以使用以下功能:
def func(x): try: return int(x) except ValueError: return x df = df.applymap(func) print(df.applymap(type))
输出:
A B 0 <class 'str'> <class 'int'> 1 <class 'int'> <class 'str'> 2 <class 'int'> <class 'int'> 3 <class 'str'> <class 'int'>
只需将数据帧转换为整数,并忽略任何会返回原始字符串的错误
再简单不过了
您可以使用以下功能:
输出:
相关问题 更多 >
编程相关推荐