访问要在理解表达式中评估的列列表

发布于 2025-02-06 23:18:29 字数 866 浏览 0 评论 0原文

有此dataframe称为frame带有列:age成熟gend> gens> gend>,height> height具有值'传递'或'失败'。

我想创建一个名为result的新列,并计算具有check_columns中的总体列的子集数量,该列中具有值传递

我尝试使用一种理解表达式,如这种情况所示,我希望将其评估为2,因为列age 成熟已经传递了 性别具有失败,这些在check_columns的列中存在。

frame = pd.DataFrame(
    data = {'Age':['PASSED'], 'Maturity':['PASSED'],'Gender':['FAILED'], 'Height':['PASSED']}
)
check_columns = ['Age','Maturity','Gender']
frame['result'] = sum([1  if frame[column] =='PASSED' else 0 for column in check_columns ])

我试图使用列表的理解力,但它说明了这个错误:

valueerror:系列的真实价值是模棱两可的。使用A.Empty,A.Bool(),A.Item(),a.any()或a.all()。

There is this dataframe called frame with columns: Age, Maturity, Gender, Height which has values 'PASSED' or 'FAILED'.

I want to create a new column called result and count the number of a subset of the overall columns as seen in check_columns which has the value PASSED.

I tried to use a comprehension expression which as seen in this case I wanted it to be evaluated to 2 since the columns Age and Maturity have PASSED while Gender has FAILED which are present in a subset of columns in check_columns.

frame = pd.DataFrame(
    data = {'Age':['PASSED'], 'Maturity':['PASSED'],'Gender':['FAILED'], 'Height':['PASSED']}
)
check_columns = ['Age','Maturity','Gender']
frame['result'] = sum([1  if frame[column] =='PASSED' else 0 for column in check_columns ])

I tried to used a comprehension with a list but it says this error:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮华 2025-02-13 23:18:29

仅选择所需的列,使用dataframe.eq检查哪些列等于“传递”,然后使用dataframe.sum.sum(Pass AXIS = AXIS =)来计数真实值1计算列的计数)

import pandas as pd

frame = pd.DataFrame(
    data = {'Age':['PASSED'], 'Maturity':['PASSED'],'Gender':['FAILED'], 'Height':['PASSED']}
)
check_columns = ['Age','Maturity','Gender']

frame['results'] = frame[check_columns].eq('PASSED').sum(axis=1)

输出:

>>> frame 

      Age Maturity  Gender  Height  results
0  PASSED   PASSED  FAILED  PASSED        2

Select only the desired columns, check which ones are equal to 'PASSED' using DataFrame.eq, and count the True values using DataFrame.sum (pass axis=1 to count column-wise)

import pandas as pd

frame = pd.DataFrame(
    data = {'Age':['PASSED'], 'Maturity':['PASSED'],'Gender':['FAILED'], 'Height':['PASSED']}
)
check_columns = ['Age','Maturity','Gender']

frame['results'] = frame[check_columns].eq('PASSED').sum(axis=1)

Output:

>>> frame 

      Age Maturity  Gender  Height  results
0  PASSED   PASSED  FAILED  PASSED        2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文