首页 > 解决方案 > 如何制作一个函数来检查与 Python 中的哪个功能相关的项目?

问题描述

我花了一天时间尝试解决以下问题,但我仍然无法找到正确的方法。这是问题示例:

import pandas as pd

cars = {'Item Id': ['101','102','103', '104'],
        'Feature 1': [1,0,1,0],
        'Feature 2': [0,0,1,0],
        'Feature 3': [1,1,1,0],
        'Feature 4': [0,0,1,1],
        }

df = pd.DataFrame(cars, columns = ['Item Id','Feature 1','Feature 2','Feature 3','Feature 4'])

df

在此处输入图像描述

我想为输入项目 ID创建一个函数,然后检查与该项目 ID相关的所有功能,并获取该项目具有的功能总数。输出样本

在此处输入图像描述

标签: pythonpandas

解决方案


DataFrame.set_indexsum和一起使用Series.reset_index

df = df.set_index('Item Id').sum(axis=1).reset_index(name='No')
print (df)
  Item Id  No
0     101   2
1     102   1
2     103   4
3     104   1

推荐阅读