[英]converting str to int
I have a text file and trying to process it.我有一个文本文件并试图处理它。 at the end I have to convert one of the variables from
str
to int
.最后,我必须将其中一个变量从
str
转换为int
。 if I print the variable using this command:如果我使用此命令打印变量:
print(y_test.iloc[:,1])
I would get the following results:我会得到以下结果:
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
and if I get the type of this variable:如果我得到这个变量的类型:
print(type(y_test.iloc[:,1]))
I would get this output:我会得到这个 output:
<class 'pandas.core.series.Series'>
but my expected output is this (A to 0 and B to 1):但我预期的 output 是这样的(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
to do so, I tried the following code:为此,我尝试了以下代码:
y2 = int(y_test.iloc[:,1])
but did not return what I want.但没有返回我想要的。 do you know how to do that?
你知道怎么做吗?
To get A as 1 and B (or anything else) as 0 you can use the below.要将 A 设为 1 并将 B(或其他任何内容)设为 0,您可以使用以下命令。 It converts all A's to True, which are then converted to the integer value of True, which is 1.
它将所有 A 转换为 True,然后将其转换为 True 的 integer 值,即 1。
(y_test.iloc[:,1] == 'A').astype(int)
You can use the method replace()
:您可以使用方法
replace()
:
y_test.iloc[:, 1].replace({'B': 0, 'A': 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.