python - 如何根据python(熊猫)中的用户输入删除列?
问题描述
如何编写代码以便数据框根据用户输入的列名删除列?
amend_col= input(" would u like to 'remove' any column?:")
if amend_col == "yes":
s_col= input("Select the column you want to add or remove:")
if s_col in df.columns:
print("Column is found and removed")
df.drop(df[s_col])
else:
print("No columns removed")
解决方案
您可以按如下方式修改您的代码:
amend_col= input(" would u like to 'remove' any column?:")
if amend_col == "yes":
s_col= input("Select the column you want to add or remove:")
if s_col in df.columns and amend_col =="yes":
print("Column is found and removed")
df = df.drop(columns=s_col)
else:
print("No columns removed")
您的代码很接近,我们只需要将行替换df.drop(df[s_col])
为
df = df.drop(columns=s_col)
推荐阅读
- swift - 我似乎无法解决 valueForUndefinedKey:] 的错误:whereto class is not key value coding-compliant
- javascript - 使用“every”测试是否已获取项目未按预期工作
- linux-device-driver - 华硕笔记本电脑 FX503:键盘背光控制在 Linux 中不起作用
- ruby-on-rails - 在 Gitlab-CI 上启动 postgres 服务
- javascript - 将字符串数组转换为对象 ID 数组
- java - 目标数据库大小在合并时翻倍
- javascript - 引导下拉菜单在 React 中不起作用
- php - 调用未定义的方法 Net_SSH2::put()
- c# - c# LINQ 为 tie 断路器创建查询以计算位置
- sql - ms sql server中where子句中的if else条件