python - 如何使用 Python 将所有列从数字转换为分类

标签 python type-conversion

我的 .csv 文件中有 51 列,我需要一次性将所有 int 64 数据类型转换为分类数据类型。我该怎么做?我是否需要提及 data[].

中的所有列名
 data[].astype('categorical')

最佳答案

您可以将列名放入列表中,然后循环更改每一列的类型。

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 - 如何使用 Python 将所有列从数字转换为分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928264/

相关文章:

python - Pandas - 按数字和字母分割并保存最后分割

python - Django-cms错误 "unsupported operand type(s) for +: '设置'和 'tuple'“

python - 如何从 pandas 数据帧的不同列中选择多个值

c++ - 显式类型转换的要求

Python Selenium StaleElementReferenceException : Message: stale element reference: element is not attached to the page document

python - 如何在主 Flask 模块之外登录?

c# - 将 double 强制转换为 long 更改值

c# - 从字符串安全转换的辅助函数

c - 整数转换(缩小,扩大),未定义的行为

c - 欧拉计划中的问题 #8