在 Pandas 数据框中将 yes/no 转换为整数类型 1/0(不仅仅是替换)

Converting yes/no to integer type 1/0 (not just replacing) in Pandas data frame

在这里看了几个post之后,每个post都解释了如何用1/0替换列中的yes/no,但是这些数字的数据类型仍然是'object' 并且不是 float 或 int(即使在我使用 astype(int) 之后),所以我无法对它们进行进一步的操作。我的代码如下。 有人知道现在如何将数据类型从对象转换为浮点数或整数吗?

df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

print(df['Inter Plan'].dtypes)

在替换之前尝试转换为 str

df['Inter Plan'] = df['Inter Plan'].str.replace({'no': 0, 'yes': 1}).astype(int)

astypereturns一个pandas系列,做的不是很到位。使用:

df["Inter Plan"] = df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

astype 有一个 copy 选项,可以让您就地进行操作,但是因为您也使用了 replace,所以我不认为您将能够在一行中完成所有操作,因此最好只使用上面的代码。此外,就地选项(将 copy 设置为 False)带有警告:

be very careful setting copy=False as changes to values then may propagate to other pandas objects.

一种方法:

df['Inter Plan'].replace({'no': 0, 'yes': 1}, inplace=True).astype('int', copy=False)