pandas 从数据框中选择列存在的条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43537166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:26:41  来源:igfitidea点击:

Select columns from dataframe on condition they exist

pythonpandasdataframe

提问by astudentofmaths

I have a pandas DataFrame with multiple columns (columns names are numbers; 1, 2, ...) and I want to copy some of them if they do exist.

我有一个包含多列的 Pandas DataFrame(列名是数字;1、2、...),如果它们确实存在,我想复制其中的一些。

For example df1 = df[[1,2,3,4]]But it might happen that some columns do not exist in df, eg df might only have columns 1, 2, and 4 or columns 1, and 2 etc

例如df1 = df[[1,2,3,4]]但可能会发生某些列在 df 中不存在的情况,例如 df 可能只有第 1、2 和 4 列或第 1 和 2 列等

回答by EdChum

Use isinwith locto filter, this will handle non-existent columns:

使用isinwithloc过滤,这将处理不存在的列:

In [97]:
df = pd.DataFrame(columns=[1,2,4])
df.loc[:,df.columns.isin([1,2,3,4,])]

Out[97]:
Empty DataFrame
Columns: [1, 2, 4]
Index: []

回答by Eric O Lebigot

It is simpler to directly calculate the set of common columns and ask for them:

直接计算公共列的集合并询问它们更简单:

df[df.columns & [1, 2, 3, 4]]