【问题标题】:How do I iterate over rows in Pandas and check if the sum of each row is equal to the sum of a list?如何遍历 Pandas 中的行并检查每行的总和是否等于列表的总和?
【发布时间】:2022-12-03 09:20:38
【问题描述】:

我努力了:

for i, row in preferences.iterrows():
    if len(students_with_courses) == preferences.sum(axis = i):

但是得到以下错误: Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

I have tried: 

对于我,preferences.iterrows() 中的行: 如果 len(students_with_courses) == preferences.sum(axis = i):

But gets following error: 
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • students_with_courses 是什么?如果不使用row,为什么要遍历行?请提供一个完全可重现的输入/输出示例

标签: pandas


【解决方案1】:

你得到你提供的错误的原因是你正在比较的是 len(students_with_courses) == preferences.sum(axis = i) 返回一个系列包含True/False值,而不是一个单一的True/False值。 if 语句需要一个单一的 True/False 值。

为了找到可行的解决方案,我对students_with_coursespreferences 的含义做了一些假设。我还假设你的意思是长度列表中的,而不是列表,因为这就是您的代码显示的内容。

students_with_courses = ["a", "b", "c"]
preferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]})

如果您只是想看看每行的总和是否等于列表的长度,您可以简化为下面的代码,而不是遍历每一行。

preferences.sum(axis=1) == len(students_with_courses)

这将返回:

0     True
1    False
2     True
3    False
dtype: bool

请注意,如果您想比较列表的而不是长度列表中,您可以使用以下代码。

students_with_courses = [1, 0, 2]
preferences = pd.DataFrame({'column1': [0, 1, 1, 3], 'column2': [0, 0, 1, 1], 'column3': [3, 6, 1, 8]})
preferences.sum(axis=1) == sum(students_with_courses)

这将返回:

0     True
1    False
2     True
3    False
dtype: bool

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 2015-02-22
    • 2015-04-19
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 2019-05-28
    • 2019-07-29
    相关资源
    最近更新 更多