如何检查 Pandas 中是否存在列 [英] How to check if a column exists in Pandas
本文介绍了如何检查 Pandas 中是否存在列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法检查 Pandas DataFrame 中是否存在列?
假设我有以下数据帧:
<预><代码>>>>将熊猫导入为 pd>>>来自随机导入 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乙丙0 3 40 1001 6 30 2002 7 70 8003 3 50 2004 7 50 4005 4 10 4006 3 70 5007 8 30 2008 3 40 8009 6 60 200我想计算 df['sum'] = df['A'] + df['C']
但首先我想检查 df['A']
是否存在,如果不存在,我想计算 df['sum'] = df['B'] +df['C']
代替.
解决方案
这会起作用:
if 'A' in df:
但为了清楚起见,我可能会写成:
if 'A' in df.columns:
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.
解决方案
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
这篇关于如何检查 Pandas 中是否存在列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文