我有一个带浮点值的数据集:
dog-auto dog-bird dog-cat dog-dog Result
41.9579761457 41.7538647304 36.4196077068 33.4773590373 0
46.0021331807 41.33958925 38.8353268874 32.8458495684 0
42.9462290692 38.6157590853 36.9763410854 35.0397073189 0
41.6866060048 37.0892269954 34.575072914 33.9010327697 0
39.2269664935 38.272288694 34.778824791 37.4849250909 0
40.5845117698 39.1462089236 35.1171578292 34.945165344 0
45.1067352961 40.523040106 40.6095830913 39.0957278345 0
41.3221140974 38.1947918393 39.9036867306 37.7696131032 0
41.8244654995 40.1567131661 38.0674700168 35.1089144603 0
45.4976929401 45.5597962603 42.7258732951 43.2422832585 0
这是一个SFrame。我试图编写一个函数,它使用if / an语句来确定dog-dog的值是否小于dog-ct和dog-auto和dog-bird的值。
我经历了4个小时的大部分时间。不可否认,我是python的新手 - 我犯了一个错误,只是没有看到它。
如果声明:
def is_dog_correct(row):
if (dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-cat']]) & (dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-bird']]) & (dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-auto']]):
dog_distances['Result'] = 1
else:
dog_distances['Result'] = 0
然后我用以下函数调用该函数:
dog_distances.apply(is_dog_correct)
如果这个工作正常,我会在每一行看到“0”,但第五条记录。我的if语句出了什么问题?
完全披露 - 这是课程作业,但在花了4个小时后,我正在寻求帮助!
答案 0 :(得分:1)
改变&amp;并且如前面的评论所示。另外,我建议你把这么长的if语句分成多行,这样就更清晰,更容易阅读。
def is_dog_correct(row):
if (dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-cat']]) and
(dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-bird']]) and
(dog_distances[dog_distances['dog-dog']] < dog_distances[dog_distances['dog-auto']]):
dog_distances['Result'] = 1
else:
dog_distances['Result'] = 0
答案 1 :(得分:0)
通过查找所有值的min
(最小值),使您的第一个if语句更加干净。这确保了“狗狗”#39;比其他所有人都少:
def is_dog_correct(row):
if dog_distances[dog_distances['dog-dog']] < min([dog_distances[dog_distances['dog-'+x]] for x in ['cat','bird','auto']]):
dog_distances['Result'] = 0
else:
dog_distances['Result'] = 1
编辑:出于调试目的,请使用以下命令:
def is_dog_correct(row):
print 'dog is {}'.format(dog_distances[dog_distances['dog-dog']])
print 'everyone else is {}'.format([dog_distances[dog_distances['dog-'+x]] for x in ['cat','bird','auto']])
if dog_distances[dog_distances['dog-dog']] < min([dog_distances[dog_distances['dog-'+x]] for x in ['cat','bird','auto']]):
print 'Yay dog is faster'
dog_distances['Result'] = 0
else:
print 'Awww, dog is not faster'
dog_distances['Result'] = 1