如何将 python 中的分类列转换为整数列? (与南)

How to convert categorical columns to integer columns in python? (with NaN)

我的数据框在下面。

id  gender  region  income  a1  a2  a3  a4  a5  a6  a7  a8  a9  a10
1   male    N        300    NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2   female  S        500    7   10  10  10  6   6   6   8   5   9
3   male    E        200    6   NaN 9   6   6   NaN 7   7   7   9
4   female  W        100    9   7   7   NaN 7   8   8   8   NaN 5

我想将多列的数据类型分类更改为整数。 (a1~a10) 所以,我尝试了下面的代码,但出现了如下错误

df.iloc[:, 4: ].astype('int')

ValueError: cannot convert float NaN to integer

我该如何隐藏它?

谢谢。

您必须继续进行删除 a 或填写 a 之前。

#will remove line with Nan inside
df.dropna(inplace=True)

或者

#will replace Nan by a value e.g "- 1" 
df.fillna(-1,inplace=True)

默认情况下 pandasnp.nan 的列转换为 float

对于 pandas 版本 0.24.0 以上

将所需的列转换为可以具有 np.nan 个值的数据类型 Int8

columns = ["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"]

df[columns] = df[columns].astype("Int8")

print(df.dtypes)

参考这个documentation

备选方案

您可以将每列的np.nan替换为mode,然后将它们转换为int

for c in columns:
    x = df[c].mode()
    x = list(x)[0]
    df[c] = df[c].fillna(x).astype("int")

您好,您可以按照以下方法:

这将用 0 填充 NaN 值,因此类型将为 int。

df.fillna(value=int(), inplace=True)

这将用<class 'int'>填充NaN值,这也是int类型。

df.fillna(value=int, inplace=True)

如果使用 pandas 0.24+ 可以使用 Nullable integer data type,也需要 .astype(float) 将分类列转换为数字:

df.iloc[:, 4: ] = df.iloc[:, 4: ].astype(float).astype("Int64")
print (df)
   id  gender region  income   a1   a2   a3   a4   a5   a6   a7   a8   a9  a10
0   1    male      N     300  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1   2  female      S     500    7   10   10   10    6    6    6    8    5    9
2   3    male      E     200    6  NaN    9    6    6  NaN    7    7    7    9
3   4  female      W     100    9    7    7  NaN    7    8    8    8  NaN    5

如有必要,用每列最常见的值替换缺失值:

df.iloc[:, 4: ] = df.iloc[:, 4: ].fillna(df.iloc[:, 4: ].mode().iloc[0]).astype(int)

print (df)
   id  gender region  income  a1  a2  a3  a4  a5  a6  a7  a8  a9  a10
0   1    male      N     300   6   7   7   6   6   6   6   8   5    9
1   2  female      S     500   7  10  10  10   6   6   6   8   5    9
2   3    male      E     200   6   7   9   6   6   6   7   7   7    9
3   4  female      W     100   9   7   7   6   7   8   8   8   5    5

假设 A1-A3 列中没有空值

cleanup_nums = {"A1":{"Apple":1, "Samsung":2}}
df.replace(cleanup_nums,inplace=True)

replace函数的详细内容可以参考https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html.

python 中也有编码分类值的教程。 https://pbpython.com/categorical-encoding.html