我有一个文本文件,正在尝试对其进行处理。最后,我必须将变量之一从str
转换为int
。
如果我使用以下命令打印变量:
print(y_test.iloc[:,1])
我会得到以下结果:
0 B
1 B
2 A
3 A
4 A
5 A
6 A
7 A
8 B
9 B
10 B
11 B
12 B
13 B
Name: group, dtype: object
,如果我得到此变量的类型:
print(type(y_test.iloc[:,1]))
我会得到以下输出:
<class 'pandas.core.series.Series'>
但是我的预期输出是(A到0和B到1):
0 0
1 0
2 1
3 1
4 1
5 1
6 1
7 1
8 0
9 0
10 0
11 0
12 0
13 0
为此,我尝试了以下代码:
y2 = int(y_test.iloc[:,1])
但没有返回我想要的。你知道怎么做吗?
答案 0 :(得分:2)
要将A设为1,将B(或其他任何东西)设为0,可以使用以下内容。它将所有A转换为True,然后将其转换为True的整数值1。
(y_test.iloc[:,1] == 'A').astype(int)
答案 1 :(得分:0)
您可以使用方法replace()
:
y_test.iloc[:, 1].replace({'B': 0, 'A': 1})