我目前正在学习一些机器学习,并使用熊猫,在其中一个例子中,他们这样做
# Get list of categorical variables
s = (X_train.dtypes == 'object')
object_cols = list(s[s].index)
print("Categorical variables:")
print(object_cols)我现在很难理解他们做ss.index时发生了什么,ss怎么可能?有人能帮帮我吗。提前感谢
这是我正在读的东西的链接:https://www.kaggle.com/alexisbcook/categorical-variables
发布于 2020-09-23 16:32:37
您可以按条件索引Series,例如myseries[myseries == 4]将返回等于4的元素。在您的例子中,如果您有一个布尔表达式,那么这两个表达式是相同的:
myseries[myseries == True]
myseries[myseries] 因此,在您的示例中,将返回属于True的所有元素的索引。
myseries = pd.Series([True, False, True, False])
x = myseries[myseries] # returns Series: (0, True) (2, True)
x = x.index # returns [0,2]在kaggle示例的上下文中,这些布尔值是由s = (X_train.dtypes == 'object')构造的,即您发布的代码片段获取object类型的每个训练示例的索引。
我个人不推荐这个快捷方式,因为它不必要地掩盖了代码,编写s[s==True]也不是很多工作。
https://stackoverflow.com/questions/64032304
复制相似问题