alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[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.

posted on   McDelfino  阅读(24)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-02-08 【457】Word2Vec,Embedding层,词嵌入
点击右上角即可分享
微信分享提示