我正在用python为一个足球联赛做一个预测模型。我刚刚找到了聚合函数。在我遇到这个问题之前,一切都很顺利:我正在尝试比较一列的某些值,如:
'column1' : 'count'
#My code
final = dataset.groupby(['Home','Away'], as_index=False).agg({'HG': ['mean'], 'AG': ['mean', 'count']})
我的一个想法是改变列的类型(可能是'count'的值),但它不起作用
我试图做的是检查,在函数中,如果之前这对数据中有更多匹配,下面是“最终”数据帧的输出示例:
Home Away HG AG
mean mean count
0 Astra Bistrita 4.000000 0.000000 1
1 Astra CFR Cluj 1.100000 2.100000 10
2 Astra CS...... 1.000000 1.000000 1
其中“计数”是指在这个公式中,“阿斯特拉对小酒馆”的比赛在几个赛季中只发生一次
我想做这样的事情(跳过这个错误之后,我想做更多):
def functie(home, away):
subset = final.loc[(final.Home==home)&(final.Away==away)]
#print(subset['AG'].count)
if (subset['AG'].count >= 1):
print("It worked")
functie('Astra', 'Bistrita')
以下是错误:
TypeError Traceback (most recent call last)
<ipython-input-46-2e7b6464c49d> in <module>
92 print("It worked")
93
---> 94 functie('Astra', 'Bistrita')
95
96 final.head(30)
<ipython-input-46-2e7b6464c49d> in functie(home, away)
89 subset = final.loc[(final.Home==home)&(final.Away==away)]
90 #print(subset['AG'].count)
---> 91 if (subset['AG'].count >= 1):
92 print("It worked")
93
TypeError: '>=' not supported between instances of 'method' and 'int'
**编辑:
如果我称之为:
subset = final.loc[(final.Home=='Astra')&(final.Away=='CFR Cluj')]
subset['AG'].count(axis = 0)
它给了我
mean 1
count 1
dtype: int64
这没关系,因为它按预期工作,它只计算了主队是“阿斯特拉”而客队是“克鲁伊”时我的排数。但是我想从AG,从'final'数据帧访问count列
好的,我设法得到了我的答案,我把它贴在这里给其他有同样问题的人。以下是我所做的:
subset['AG'].count
是应用于subset['AG']
的pandascount
方法。由于它是在没有()
的情况下编写的,因此它提供了方法本身,而不是它的任何结果您显然想做的是访问
subset
数据帧的一列。该数据帧的列上有一个多索引,这意味着您可以使用列名元组访问单个列所以在你的代码中
应替换为
这解决了在您的版本中,
count
被解释为方法名,而您希望它表示列名的歧义但是,请注意
subset['AG', 'count'] >= 1
将为您提供一个布尔序列,因为该列的每个值都将与1进行比较。因此,您仍然需要考虑if
条件到底应该是什么相关问题 更多 >
编程相关推荐