Python:如何将列中只有数字成分的字符串项转换为整数?

2024-09-27 00:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有字符串类型列的数据框,其中包含字符和数字条目

下面是一个示例df:

A        B
101a5    12222
11111    e2edw2
22222    33333
asxaa    0045

我想将字符串中只有数值的条目转换为整数,但将其余条目保留为字符串

最好的方法是什么

提前谢谢


Tags: 数据方法字符串示例类型df条目数字
2条回答

只需将数据帧转换为整数,并忽略任何会返回原始字符串的错误

再简单不过了

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

相关问题 更多 >

    热门问题