How to Extract Numbers from Strings in Pandas Using str.extract()?

Mary-Kate Olsen
Release: 2024-10-24 13:06:31
Original
428 people have browsed it

How to Extract Numbers from Strings in Pandas Using str.extract()?

Extracting Numbers from Strings in Pandas

To extract numbers from strings within a Pandas data frame, consider utilizing the str.extract method. This method enables the usage of regular expressions to extract specific patterns from a data frame's string values.

In the provided example, the df data frame contains a column 'A' with mixed data types, including strings containing numbers. To extract only the numbers, a regex capture group can be employed:

<code class="python">df.A.str.extract('(\d+)')</code>
Copy after login

The regular expression pattern (d ) specifies a capture group that matches one or more digits (d). This will isolate the numbers within each string.

The result is a new data frame column containing the extracted numbers:

    A
0   1
1   NaN
2   10
3   100
4   0
Copy after login

Note that this method will only work for whole numbers and not floats. For more complex patterns or cases where the numbers are separated by non-digits, additional regular expression syntax may be required.

The above is the detailed content of How to Extract Numbers from Strings in Pandas Using str.extract()?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!