如何在行中计算“Y”?

huangapple go评论131阅读模式
英文:

How to counts "Y" in Row?

问题

如何在Python中计算并更新包含新列的“y”值的数量。

示例:
从第3列到第7列查找值为“y”,然后更新最后一列的计数。

如图所示。

英文:

How to counts "y" value in python and update this output new column.

Example:-
col 3 to col 7 find the value "y" and update the counts the last col.

like this image.

如何在行中计算“Y”?

答案1

得分: 3

如果你想在按行级别计算所有的 'Y'你可以使用以下条件

df['counts'] = (df == 'Y').sum(axis=1)


如果你想指定特定的列,你可以使用以下条件:

df['counts'] = (df[['INR', 'USA', 'UK', 'SA', 'ENG']] == 'Y').sum(axis=1)

英文:

if you are looking to calculate all the 'Y' in row-wise level then you can use the below condition:


df['counts']=(df == 'Y').sum(axis=1)

if you want to mention specific columns then u can use the below condition:

df['counts']=(df[['INR','USA','UK','SA','ENG']]=='Y').sum(axis=1)

答案2

得分: 0

筛选字符串列:

# 筛选对象列
cols = list(filter(lambda x: df[x].dtype == 'object', df.columns))

然后,计算 Y 的数量并在行上求和:

y_count = df[cols].apply(lambda x: x.str.count('Y')).sum(axis=1)

最后,将结果分配给新列 counts

df = df.assign(counts = y_count)
print(df)
英文:

First filter string columns:

# filter object columns
cols = list(filter(lambda x: df[x].dtype == 'object', df.columns))

Then, count the number of Y and sum across the row

y_count = df[cols].apply(lambda x: x.str.count('Y')).sum(axis=1)

Finally, assign to the new column as counts

df = df.assign(counts = y_count)
print(df)

huangapple
  • 本文由 发表于 2023年7月24日 19:42:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76754139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定