【问题标题】:Dropping pandas dataframe columns删除熊猫数据框列
【发布时间】:2019-04-28 06:52:13
【问题描述】:

我正在尝试从数据框中删除列但不起作用。

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)  

new_df 应该保留数据和列名、性别和年龄。

【问题讨论】:

标签: python django


【解决方案1】:

Suyash 的回答应该有效。如果您有要放入字符串的列列表,则需要注意在拆分后去除空格。

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

【讨论】:

    【解决方案2】:

    假设你想放弃 您可以通过两种方式做到这一点。

    1. 使用 drop 删除例如两列 a 和 b
    import pandas as pd 
    df=pd.read_csv('filename') 
    df=df.drop(columns=["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]
    

    【讨论】:

    • 我的问题是列在一个字符串中。 columns_to_retain = 'name, sex, age'。如何在数据框中插入它?
    • @dJudge 由于您的列名都在一个字符串中,您需要做的是通过拆分“,”将它们转换为列表,然后将列表作为参数传递。我已根据您的要求编辑了我的答案。希望对你有帮助
    猜你喜欢
    • 1970-01-01
    • 2020-05-28
    • 2018-03-15
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多