Python:如何将列中仅包含数字组件的字符串条目转换为整数?

标签 python string pandas integer

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

下面是一个 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'>

关于Python:如何将列中仅包含数字组件的字符串条目转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60253313/

相关文章:

python - 比较后如何从数据框中删除行

python - 用什么来替换 python 中的接口(interface)/协议(protocol)

python - 为什么此代码在 Python 3 中速度较慢?

python - Flask+Apache 和 500 错误

python - 在一个类中使用 HasTraits 和 PyQt 信号

excel - 如何将字符串公式转换为 "real"公式?

c - 为什么这个 Perl 循环遍历字符串然后字符这么慢?

javascript - 如何使用 parseFloat 将字符串转换为数字?

python - 在条件 Pandas 的新列中分配值

Python Pandas 多索引值不会在数据透视表中移动