[968] Pandas, Data Frame, dtypes
In Pandas, you can use the dtypes
attribute of a DataFrame to get the data type of each column. Here's how you can do it:
import pandas as pd # Create a sample DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22], 'Salary': [50000, 60000, 45000]} df = pd.DataFrame(data) # Get the data type of each column column_types = df.dtypes print(column_types)
This will output:
Name object Age int64 Salary int64 dtype: object
In this example, the dtypes
attribute returns a Series where the index corresponds to the column names, and the values are the data types of each column.
In Pandas, you can use the astype()
method to change the data type of a column in a DataFrame. Here's how you can do it:
import pandas as pd # Create a sample DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22], 'Salary': [50000, 60000, 45000]} df = pd.DataFrame(data) # Display the original DataFrame print("Original DataFrame:") print(df) # Change the data type of the 'Age' column to float df['Age'] = df['Age'].astype(float) # Display the DataFrame after changing the data type print("\nDataFrame after changing 'Age' column data type:") print(df)
This will output:
Original DataFrame: Name Age Salary 0 Alice 25 50000 1 Bob 30 60000 2 Charlie 22 45000 DataFrame after changing 'Age' column data type: Name Age Salary 0 Alice 25.0 50000 1 Bob 30.0 60000 2 Charlie 22.0 45000
In this example, the astype(float)
method is used to change the data type of the 'Age' column to float. You can replace float
with the desired data type, such as int
, str
, etc., based on your requirements.
分类:
Python Study
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2020-02-08 【457】Word2Vec,Embedding层,词嵌入