12/1/2023 0 Comments Convert string to integer r![]() ![]() You’ll now notice the NaN value, where the data type is float: Product Price Here is the Python code: import pandas as pdĭf = pd.to_numeric(df,errors='coerce') In that case, you can still use to_numeric in order to convert the strings: df = pd.to_numeric(df, errors='coerce')īy setting errors=’coerce’, you’ll transform the non-numeric values into NaN. What if your column contains a combination of numeric and non-numeric values?įor example, in the DataFrame below, there are both numeric and non-numeric values under the Price column: Product ![]() You’ll now see that the values under the Price column are indeed integers: Product Price Price int32 Step 3 (optional): Convert the Strings to Integers using to_numericįor this optional step, you may use the second approach of to_numeric to convert the strings to integers: df = pd.to_numeric(df)Īnd this is the complete Python code to perform the conversion: import pandas as pd So this is the complete Python code that you may apply to convert the strings into integers in Pandas DataFrame: import pandas as pdĪs you can see, the values under the Price column are now integers: Product Price Since in our example the ‘DataFrame Column’ is the Price column (which contains the strings values), you’ll then need to add the following syntax: df = df.astype(int) You may use the first approach of astype(int) to perform the conversion: df = df.astype(int) Now how do you convert those strings values into integers? Price object Step 2: Convert the Strings to Integers in Pandas DataFrame When you run the code, you’ll notice that indeed the values under the Price column are strings (where the data type is object): Product Price This is how the DataFrame would look like in Python: import pandas as pd You can capture the values under the Price column as strings by placing those values within quotes. ![]() To start, let’s say that you want to create a DataFrame for the following data: Product Steps to Convert Strings to Integers in Pandas DataFrame Step 1: Create a DataFrame Let’s now review few examples with the steps to convert strings into integers. (2) The to_numeric approach: df = pd.to_numeric(df) (1) The astype(int) approach: df = df.astype(int) ![]() In this guide, you’ll see two approaches to convert strings into integers in Pandas DataFrame: ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |