Pandas:用 0 替换非数字单元格

Has*_*ikh 5 python pandas

我有这种格式的 Pandas Dataframe

0          or LIST requests
1                 us-west-2
2                 1.125e-05
3                         0
4                 3.032e-05
5                         0
6                  7.28e-06
7          or LIST requests
8                   3.1e-07
9                         0
10                        0
11                1.067e-05
12               0.00011983
13                0.1075269
14         or LIST requests
15                us-west-2
16                        0
17                 2.88e-06
18           ap-northeast-2
19                 5.52e-06
20                 6.15e-06
21                 3.84e-06
22         or LIST requests
Run Code Online (Sandbox Code Playgroud)

我想用 0 替换熊猫中的所有非数字单元格。我正在尝试这样的事情,但没有任何效果,

training_data['usagequantity'].replace({'^([A-Za-z]|[0-9]|_)+$': 0}, regex=True)
Run Code Online (Sandbox Code Playgroud)

任何提示我该怎么做:

mgi*_*gig 8

您可以使用该to_numeric方法,但它不会就地更改值。您需要将该列设置为新值:

training_data['usagequantity'] = (
    pd.to_numeric(training_data['usagequantity'],
                  errors='coerce')
      .fillna(0)
    )
Run Code Online (Sandbox Code Playgroud)

to_numeric将非数字值设置为NaNs,然后链式fillna方法NaNs用零替换。


小智 8

以下代码可以工作:

df.col =pd.to_numeric(df.col, errors ='coerce').fillna(0).astype('int')
Run Code Online (Sandbox Code Playgroud)


piR*_*red 4

设置

import pandas as pd
from StringIO import StringIO

text = """0          or LIST requests
1                 us-west-2
2                 1.125e-05
3                         0
4                 3.032e-05
5                         0
6                  7.28e-06
7          or LIST requests
8                   3.1e-07
9                         0
10                        0
11                1.067e-05
12               0.00011983
13                0.1075269
14         or LIST requests
15                us-west-2
16                        0
17                 2.88e-06
18           ap-northeast-2
19                 5.52e-06
20                 6.15e-06
21                 3.84e-06
22         or LIST requests"""

df = pd.read_csv(StringIO(text), sep='\s{2,}', engine='python', index_col=[0], header=None)
Run Code Online (Sandbox Code Playgroud)

使用pd.to_numeric

pd.to_numeric(df.iloc[:, 0], errors='coerce').fillna(0)
Run Code Online (Sandbox Code Playgroud)

将此列分配到您想要的任何位置。

  • @HassamSheikh“不工作”是什么意思?你有错误吗?意想不到的结果?这个答案正是您的问题所需要的。 (2认同)