Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

python - 从pandas DataFrame删除列(Delete column from pandas DataFrame)

When deleting a column in a DataFrame I use:

(在删除DataFrame中的列时,我使用:)

del df['column_name']

And this works great.

(这很棒。)

Why can't I use the following?

(为什么不能使用以下内容?)

del df.column_name

As you can access the column/Series as df.column_name , I expect this to work.

(因为您可以使用df.column_name来访问列/系列, df.column_name我希望这可以正常工作。)

  ask by John translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best way to do this in pandas is to use drop :

(在熊猫中做到这一点的最好方法是使用drop :)

df = df.drop('column_name', 1)

where 1 is the axis number ( 0 for rows and 1 for columns.)

(其中1编号( 0代表行, 1代表列)。)

To delete the column without having to reassign df you can do:

(要删除该列而不必重新分配df您可以执行以下操作:)

df.drop('column_name', axis=1, inplace=True)

Finally, to drop by column number instead of by column label , try this to delete, eg the 1st, 2nd and 4th columns:

(最后,要按列而不是按列标签删除,请尝试将其删除,例如第一,第二和第四列:)

df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index 

Also working with "text" syntax for the columns:

(还可以对列使用“文本”语法:)

df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...