Python 删除数据帧列

Python 删除数据帧列,python,django,Python,Django,我试图从数据帧中删除列,但不起作用 columns_to_retain = 'name, sex, age' # a string of columns # which will not be dropped # from the dataframe x_cols = columns_to_retain.split(',')

我试图从数据帧中删除列,但不起作用

columns_to_retain = 'name, sex, age'    # a string of columns 
                                        # which will not be dropped 
                                        # from the dataframe
x_cols = columns_to_retain.split(',') 

new_df = df.drop(columns = not x_cols)  

新的_df
应该保留数据和列名称、性别和年龄。

假设您想删除 您可以通过两种方式完成此操作。

  • 使用液滴移除两个色谱柱a和b
  • 2.只选择要显示的列

    import pandas as pd
     df=pd.read_csv('filename')
     new_df=df[["name","sex","age"]]
    
    就你而言

    columns_to_retain = 'name, sex, age'
    
    x_cols = [col.strip() for col in columns_to_retain.split(',')]#column.strip ensures that that are no leading or trailing white space in the words
    
    new_df=df[x_cols]
    

    苏亚什的答案应该有效。如果您有要放入字符串中的列列表,则需要注意在拆分后剥离空白

    df = pd.DataFrame([[4, 5, 5], [4,6,7]], columns=['a', 'b', 'c'])
    
    to_drop = 'b, c'
    to_drop_stripped = [x.strip() for x in to_drop.split(',')]
    df.drop(columns=to_drop_stripped)
    
    Result:
       a
    0  4
    1  4
    
    

    我的问题的可能重复之处在于,列位于字符串中<代码>列到保留='姓名、性别、年龄'。如何在数据框中插入它?@dJudge由于您的列名都在一个字符串中,您需要做的是通过在“,”上拆分将它们转换为列表,然后将列表作为参数传递。我已经根据你的要求编辑了我的答案。希望能有帮助
    df = pd.DataFrame([[4, 5, 5], [4,6,7]], columns=['a', 'b', 'c'])
    
    to_drop = 'b, c'
    to_drop_stripped = [x.strip() for x in to_drop.split(',')]
    df.drop(columns=to_drop_stripped)
    
    Result:
       a
    0  4
    1  4