python - 如何制作一个函数来检查与 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相关的所有功能,并获取该项目具有的功能总数。输出样本
解决方案
DataFrame.set_index
与sum
和一起使用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
推荐阅读
- php - 浏览器上的值与存储在数据库 php 中的值不同
- mongodb - 恢复到副本集时 mongorestore 挂起
- arduino - 从 Arduino Uno 切换到 NodeMCU esp8266 的 LED 灯条颜色更改代码不起作用
- curl - How to send environment variables using curl
- sql - 查询以将 SQL 表输出到 Excel 或 CSV
- angular - 为什么 Ngrx 实体 ID 通常用作字符串?
- sql - Max() 没有过滤掉 MIN()
- kubernetes - 按 pod 名称过滤 Kubernetes API
- node.js - Nodejs - 第一个参数必须是字符串或缓冲区
- javascript - 使用 Meteor JS 实现 Android 推送通知有哪些选择