Python 如何检查 Pandas 中是否存在列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24870306/
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
How to check if a column exists in Pandas
提问by npires
Is there a way to check if a column exists in a Pandas DataFrame?
有没有办法检查 Pandas DataFrame 中是否存在列?
Suppose that I have the following DataFrame:
假设我有以下 DataFrame:
>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
'B': [randint(1, 9)*10 for x in xrange(10)],
'C': [randint(1, 9)*100 for x in xrange(10)]})
>>> df
A B C
0 3 40 100
1 6 30 200
2 7 70 800
3 3 50 200
4 7 50 400
5 4 10 400
6 3 70 500
7 8 30 200
8 3 40 800
9 6 60 200
and I want to calculate df['sum'] = df['A'] + df['C']
我想计算 df['sum'] = df['A'] + df['C']
But first I want to check if df['A']
exists, and if not, I want to calculate df['sum'] = df['B'] + df['C']
instead.
但首先我想检查是否df['A']
存在,如果不存在,我想改为计算df['sum'] = df['B'] + df['C']
。
采纳答案by chrisb
This will work:
这将起作用:
if 'A' in df:
But for clarity, I'd probably write it as:
但为了清楚起见,我可能会写成:
if 'A' in df.columns:
回答by C8H10N4O2
To check if one or morecolumns all exist, you can use set.issubset
, as in:
要检查一列或多列是否都存在,您可以使用set.issubset
,如下所示:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
正如@brianpck 在评论中指出的那样,set([])
也可以用花括号构造,
if {'A', 'C'}.issubset(df.columns):
See this questionfor a discussion of the curly-braces syntax.
有关花括号语法的讨论,请参阅此问题。
Or, you can use a list comprehension, as in:
或者,您可以使用列表推导式,例如:
if all([item in df.columns for item in ['A','C']]):
回答by Gerges
Just to suggest another way without using if statements, you can use the get()
method for DataFrame
s. For performing the sum based on the question:
只是为了建议不使用 if 语句的另一种方法,您可以使用s的get()
方法DataFrame
。根据问题执行求和:
df['sum'] = df.get('A', df['B']) + df['C']
The DataFrame
get method has similar behavior as python dictionaries.
该DataFrame
get方法也有类似的行为,Python字典。