欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2024/9/27 python 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python 如何转换dataframe列的类型_如何使用Python将所有列从数值转换为分类 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

可以将列名放入列表中,然后循环以更改每列的类型。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

总结

以上是生活随笔为你收集整理的python 如何转换dataframe列的类型_如何使用Python将所有列从数值转换为分类的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。