Python pandas 将所有数值列中的任何字符串值替换为常量

python pandas replace any string value in all the numeric column with constant

提问人:Kavya shree 提问时间:11/17/2023 更新时间:11/17/2023 访问量:64

问:

作为数据清理的一部分,数据集有 100+ 列,并希望检查是否有任何数值/浮点列具有字符串值,并将其全部替换为常量数值。

数据:

数据1 col1 col2 中心
美国广播公司(ABC) 0.123 234 678 -123
美国广播公司(ABC) 0.1345 678 900 -0.456
def -0.454 OVG公司 测试 8.67
def 失败 NVT技术 测试 6.90
def 失败 890 900 532

将任何数值列中的任何字符串替换为 -1111 输出:

数据1 col1 col2 中心
美国广播公司(ABC) 0.123 234 678 -123
美国广播公司(ABC) 0.1345 678 900 -0.456
def -0.454 -1111 -1111 8.67
def -1111 -1111 -1111 6.90
def -1111 890 900 532

帮助在python pandas中编码

python-3.x pandas 数据帧 替换

评论

0赞 Nick 11/17/2023
你怎么知道哪些列是数字?

答:

0赞 Panda Kim 11/17/2023 #1

pd.to_numericapply

out = df.set_index('data1').apply(pd.to_numeric, errors='coerce')\
        .fillna(-1111).reset_index()

外:

    data1   col1        col2    left    center
0   abc     0.1230      234.0   678.0   -123.000
1   abc     0.1345      678.0   900.0   -0.456
2   def     -0.4540     -1111.0 -1111.0 8.670
3   def     -1111.0000  -1111.0 -1111.0 6.900
4   def     -1111.0000  890.0   900.0   532.000

示例代码

当询问有关 dtypes 的问题时,应以代码形式提供输入,而不是以文本形式提供。

import pandas as pd
data1 = {'data1': {0: 'abc', 1: 'abc', 2: 'def', 3: 'def', 4: 'def'}, 
         'col1': {0: '0.123', 1: '0.1345', 2: '-0.454', 3: 'fail', 4: 'fail'}, 
         'col2': {0: '234', 1: '678', 2: 'OVG', 3: 'NVT', 4: '890'}, 
         'left': {0: '678', 1: '900', 2: 'testing', 3: 'test', 4: '900'}, 
         'center': {0: -123.0, 1: -0.456, 2: 8.67, 3: 6.9, 4: 532.0}}
df = pd.DataFrame(data1)