Let’s say we have a DataFrame where a column contains integers. Now, we want to change the data type of the column to string or float. Or, let’s say we have multiple columns of a DataFrame and each column contains an integer. Now, we want to change the data type of every column. One column should contain an integer, another should contain a float and the other should contain a string. We can use the DataFrame.astype() function to do the same using the pandas Python library.
Let’s look at the following example.
import pandas list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] df1 = pandas.DataFrame(list1) print("df1: \n", df1) df2 = df1.astype(str) print("df2: \n", df2)
here, all the columns of df1 contain integers. Now, we want to change the data type of all the columns to string. We are using the df1.astype(str) function for the purpose.
The output of the above program will be:
df1: 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 df2: 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9
Now, let’s look at another example…






0 Comments