簡體   English   中英

Pandas:用 0 替換非數字單元格

[英]Pandas: Replacing Non-numeric cells with 0

我有這種格式的 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

我想用 0 替換熊貓中的所有非數字單元格。 我正在嘗試這樣的事情,但沒有任何效果,

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

任何提示我該怎么做:

您可以使用to_numeric方法,但它不會就地更改值。 您需要將列設置為新值:

training_data['usagequantity'] = (
    pd.to_numeric(training_data['usagequantity'],
                  errors='coerce')
      .fillna(0)
    )

to_numeric將非數字值設置為NaNs ,然后鏈式fillna方法用零替換NaNs

設置

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)

使用pd.to_numeric

pd.to_numeric(df.iloc[:, 0], errors='coerce').fillna(0)

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

以下代碼可以工作:

df.col =pd.to_numeric(df.col, errors ='coerce').fillna(0).astype('int')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM