如何根据pythonpandas中的用户输入删除列?

问题描述

如何编写代码使数据框根据用户输入的列名删除列?

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)
,
amend_col= input("Would u like to 'remove' any column?:")
# Maybe check case or input type
if amend_col == "yes":
   s_col= input("Select the column you want to add or remove:")
   # Again maybe check case,put all the col ids to uppercase
   try:
      df.drop([s_col],axis=1)
      print("Column {} has been found and removed.".format(s_col))
   except:
      print("Column {} does not exist.\nNo columns have been removed.".format(s_col))
else:
    print("No columns removed.")

您可以将代码移到 try,except 替换 if s_col in df.columns and amend_col =="yes": ...。首先,您不需要检查 and amend_col =="yes",因为它已在之前的 if 语句中检查过。其次,try,except 执行相同的功能并提供反馈。

你也可以用 if 来实现:

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([s_col],axis=1)
   else:
      print("Column was not found")
else:
    print("No columns removed")
,

您不需要在第二个语句中再次写入 amend_col == 'yes',因为您已经通过了第一个。

此外,您还需要指定要在哪个轴上进行删除,在您的情况下是轴 = 1,因为您要删除一列。

所以你的代码将是这样的......

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 = df.drop(s_col,axis=1)
    else:
        print("Column is not in the dataframe."
else:
    print("No columns removed")