[英]Changing the values in csv file when loaded using pandas. (Trying to understand a code presented on a blog)
I wanted to understand the below code. 我想了解以下代码。
First these codes are taken from a blog that I currently read about google BERT. 首先,这些代码取材自我目前阅读的有关google BERT的博客。
https://medium.com/swlh/a-simple-guide-on-using-bert-for-text-classification-bbf041ac8d04 https://medium.com/swlh/a-simple-guide-on-using-bert-for-text-classification-bbf041ac8d04
The dataset can be download in the blog or from the link above. 可以在博客中或从上面的链接下载数据集。
import pandas as pd
train_df = pd.read_csv('data/train.csv', header=None)
test_df = pd.read_csv("data/test.csv", header=None)
train_df[0] = (train_df[0] == 2).astype(int) #This is the part that I do not understand. I thought this code "(train_df[0] == 2)" will find all the values with "2" but since they did not specify what it should be converted to then how can everything changed from 2 --> 0?
train_df.head()
Current results: 当前结果:
0 1
0 1 Unfortunately, the frustration of being Dr. Go...
1 0 Been going to Dr. Goldberg for over 10 years. ...
2 1 I don't know what Dr. Goldberg was like before...
3 1 I'm writing this review to give you a heads up...
4 0 All the food is great here. But the best thing...
I just wanted to understand the usage of the code and why it could success so I do not have any expected results. 我只是想了解代码的用法以及为什么它能成功,所以我没有任何预期的结果。
The below code checks if value is 2 or not and converts to int. 下面的代码检查value是否为2并转换为int。 if value is 2 ie it is True and it will be converted to 1. Otherwise it is False and it will be converted to 0.
如果value是2,即它为True,它将转换为1。否则,它为False,它将转换为0。
int() turns the boolean into 1 (True) or 0 (False). int()将布尔值转换为1(真)或0(假)。
train_df[0] = (train_df[0] == 2).astype(int)
>>>t_df[0]
0 1
1 2
2 1
3 1
4 2
Name: 0, dtype: int64
>>>t_df[0]==2
0 False
1 True
2 False
3 False
4 True
Name: 0, dtype: bool
>>>(t_df[0]==2).astype(int)
0 0
1 1
2 0
3 0
4 1
Name: 0, dtype: int64
That code will compare with 2 ( ==2 ) and convert the bool(False, True) values to int (0,1) values ( .astype(int) ) 该代码将与2( == 2 ) 比较 并将 bool(False,True)值转换为int(0,1)值( .astype(int) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.