如何根据 python (pandas) 中的用户输入删除列?

How to remove columns based on user input in python (pandas)?

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

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")