英文:
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.
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论