删除pandas数据帧列

问题描述 投票:-1回答:2

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

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
2个回答
0
投票

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


0
投票

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

  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]
© www.soinside.com 2019 - 2024. All rights reserved.