python 如何转换dataframe列的类型_如何使用Python将所有列从数值转换为分类

这篇博客展示了如何使用Python将DataFrame的所有列从数值类型转换为分类类型。通过循环遍历列名并应用astype方法,可以实现数据类型的转换。示例代码创建了一个包含整数的DataFrame,并将其所有列转换为category类型。
摘要由CSDN通过智能技术生成

可以将列名放入列表中,然后循环以更改每列的类型。import pandas as pd

import numpy as np

# create example dataframe

cats = ['A', 'B', 'C', 'D', 'E']

int_matrix = np.random.randint(10, size=(7,5))

df = pd.DataFrame(data = int_matrix, columns=cats)

print("Original example data\n")

print(df)

print(df.dtypes)

# get column names of data frame in a list

col_names = list(df)

print("\nNames of dataframe columns")

print(col_names)

# loop to change each column to category type

for col in col_names:

df[col] = df[col].astype('category',copy=False)

print("\nExample data changed to category type")

print(df)

print(df.dtypes)

这个小程序的输出是:Original example data

A B C D E

0 0 4 9 2 9

1 2 5 2 4 1

2 1 1 0 5 7

3 1 2 5 4 0

4 9 2 6 5 3

5 3 3 2 1 7

6 6 0 8 7 3

A int32

B int32

C int32

D int32

E int32

dtype: object

Names of dataframe columns

['A', 'B', 'C', 'D', 'E']

Example data changed to category type

A B C D E

0 0 4 9 2 9

1 2 5 2 4 1

2 1 1 0 5 7

3 1 2 5 4 0

4 9 2 6 5 3

5 3 3 2 1 7

6 6 0 8 7 3

A category

B category

C category

D category

E category

dtype: object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值