![]() My_array = np.array(,])ĭf = df.astype(int) To achieve this goal, you can use astype(int) as captured below: import numpy as np What if you’d like to convert some of the columns in the DataFrame from objects/strings to integers?įor example, suppose that you’d like to convert the last 3 columns in the DataFrame to integers. Name object Age object Birth Year object Graduation Year object Let’s check the data types of all the columns in the new DataFrame by adding df.dtypes to the code: import numpy as npĬurrently, all the columns under the DataFrame are objects/strings: Name Age Birth Year Graduation Year Here is the new DataFrame: Name Age Birth Year Graduation Year You can then use the following syntax to convert the NumPy array to a DataFrame: import numpy as np Here is the new array with an object dtype: Let’s now create a new NumPy array that will contain a mixture of strings and numeric data (where the dtype for this array will be set to object): import numpy as np You’ll now see the index on the left side of the DataFrame: Column_A Column_B Column_CĪrray Contains a Mix of Strings and Numeric Data So here is the complete code to convert the array to a DataFrame with an index: import numpy as npĭf = pd.DataFrame(my_array, columns =, index = ) What if you’d like to add an index to the DataFrame?įor instance, let’s add the following index to the DataFrame: index = Step 3 (optional): Add an Index to the DataFrame ![]() You’ll now get a DataFrame with 3 columns: Column_A Column_B Column_C You can now convert the NumPy array to Pandas DataFrame using the following syntax: import numpy as npĭf = pd.DataFrame(my_array, columns = ) Step 2: Convert the NumPy Array to Pandas DataFrame Run the code in Python, and you’ll get the following NumPy array: Steps to Convert a NumPy Array to Pandas DataFrame Step 1: Create a NumPy Arrayįor example, let’s create the following NumPy array that contains only numeric data (i.e., integers): import numpy as np ![]() ![]() In this short guide, you’ll see how to convert a NumPy array to Pandas DataFrame. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |