如何检查 pandas 中是否存在列 [英] How to check if a column exists in Pandas

查看:135
本文介绍了如何检查 pandas 中是否存在列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检查Pandas DataFrame中是否存在列?



假设我有以下DataFrame:

 >>>将大熊猫导入为pd 
>>>从随机导入randint
>>>> df = pd.DataFrame({'A':xrange(10)中的x的[randint(1,9)],
'B':[randint(1,9)* 10 for x in xrange )],
'C':[randint(1,9)* 100 for x in xrange(10)]})
>>> df
ABC
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']



感谢您的帮助。

解决方案

这将工作:

 如果df中的'A':

但为了清楚起见,我可能会写:

 如果df.columns中的A:


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.

Thanks for the help.

解决方案

This will work:

if 'A' in df:

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

if 'A' in df.columns:

这篇关于如何检查 pandas 中是否存在列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆