问题:如何检查熊猫中是否存在列

有没有一种方法可以检查Pandas 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

我想计算 df['sum'] = df['A'] + df['C']

但是首先我要检查是否df['A']存在,如果不存在,我要计算df['sum'] = df['B'] + df['C']

Is there a way to check if a column exists in a Pandas DataFrame?

Suppose that I have the following 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']

But first I want to check if df['A'] exists, and if not, I want to calculate df['sum'] = df['B'] + df['C'] instead.


回答 0

这将起作用:

if 'A' in df:

但是为了清楚起见,我可能将其写为:

if 'A' in df.columns:

This will work:

if 'A' in df:

But for clarity, I’d probably write it as:

if 'A' in df.columns:

回答 1

要检查是否存在全部一列或多列,可以使用set.issubset,如下所示:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

正如@brianpck在评论中指出的那样,set([])也可以使用花括号来构造它,

if {'A', 'C'}.issubset(df.columns):

有关大括号语法的讨论,请参见此问题

或者,您可以使用列表推导,如:

if all([item in df.columns for item in ['A','C']]):

To check if one or more columns all exist, you can use set.issubset, as in:

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,

if {'A', 'C'}.issubset(df.columns):

See this question for 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']]):

回答 2

只是建议另一种方法而不使用if语句,您可以将get()方法用于DataFrames。根据问题求和:

df['sum'] = df.get('A', df['B']) + df['C']

DataFrameget方法也有类似的行为,Python字典。

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。