alex_bn_lee

导航

[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 2024-02-08 14:01  McDelfino  阅读(4)  评论(0编辑  收藏  举报