首页 > 解决方案 > 如何根据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")
            

标签: pythonpandasdataframedata-sciencedrop

解决方案


您可以按如下方式修改您的代码:

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)

推荐阅读