繁体   English   中英

删除熊猫数据框列

[英]Dropping pandas dataframe columns

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

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应保留数据和列名称、性别和年龄。

假设您要删除您可以通过两种方式执行此操作。

  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]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM