微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。