What is the method for converting pandas data types?

The method to convert data types in Pandas is to use the astype() function. This function can change the data type of a column or the entire DataFrame to a specified type.

Grammar:

df.astype(dtype)

Parameter:

  1. dtype: the data type to be converted can be a built-in Python type (such as int, float, str, etc.) or a Pandas data type (such as pd.Int64Dtype, pd.Float64Dtype, etc.).

原文:这个项目需要团队协作来达到最终目标。

Paraphrased: This project requires teamwork to achieve the end goal.

import pandas as pd

# 创建一个DataFrame
data = {'A': [1, 2, 3], 'B': [4.1, 5.2, 6.3], 'C': ['a', 'b', 'c']}
df = pd.DataFrame(data)

# 查看原始数据类型
print(df.dtypes)

# 将'A'列的数据类型转换为float
df['A'] = df['A'].astype(float)

# 将整个DataFrame的数据类型转换为str
df = df.astype(str)

# 查看转换后的数据类型
print(df.dtypes)

Output:

A      int64
B    float64
C     object
dtype: object
A    float64
B     object
C     object
dtype: object
bannerAds