Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

python - Pandas: Replacing Non-numeric cells with 0

I have the Pandas Dataframe in this format

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

I want to replace all non-numeric cells with 0 in pandas. I am trying some thing like this but nothing works,

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

any hint how can I do this:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the to_numeric method, but it's not changing the value in place. You need to set the column to the new values:

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

to_numeric sets the non-numeric values to NaNs, and then the chained fillna method replaces the NaNs with zeros.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...