更改Pandas Dataframe中一列或多列的数据类型

在本教程中,我们将学习一种或多种列数据类型到另一种数据类型的转换。我们将使用DataFrame.astype()方法。

我们必须传递来自Python,Pandas或Numpy的任何数据类型以更改列元素的数据类型。我们还可以提供选定列的字典来更改特定列元素的数据类型。让我们看一下带有代码的示例。

示例

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Nhooo', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# we will change the data type of all columns to str
data_frame = data_frame.astype(str)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

输出结果

所有列数据类型都更改为str对象。如果运行上面的程序,您将得到以下结果。

No     object
Name   object
Age    object
dtype: object

现在,让我们尝试将Age列的数据类型从int更改为str。我们必须创建一个字典,以指定列名和所需的数据类型。

示例

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Nhooo', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# creating a dictionary with column name and data type
data_types_dict = {'Age': str}
# we will change the data type of Age column to str by giving the dict to the astype method
data_frame = data_frame.astype(data_types_dict)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

输出结果

如果看到输出,则仅Age列数据类型从int更改为str。请参阅下面的结果。

No      int64
Name   object
Age    object
dtype: object

结论

如果您在遵循本教程方面遇到任何困难,请在评论部分中提及它们。