pandas :添加列(如果不存在) [英] Pandas: Add column if does not exists
本文介绍了 pandas :添加列(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是刚接触熊猫的人,正在编写一个脚本,在其中读取数据框,然后对某些列进行一些计算.
I'm new to using pandas and am writing a script where I read in a dataframe and then do some computation on some of the columns.
有时候,我会看到名为"Met"的列:
Sometimes I will have the column called "Met":
df = pd.read_csv(File, sep='\t', compression='gzip', header=0, names=["Chrom", "Site", "coverage", "Met"])
有时我会:
df = pd.read_csv(File, sep='\t', compression='gzip', header=0, names=["Chrom", "Site", "coverage", "freqC"])
我需要对"Met"列进行一些计算,因此如果不存在,我将使用以下方法进行计算:
I need to do some computation with the "Met" column so if it isn't present I will need to calculate it using:
df['Met'] = df['freqC'] * df['coverage']
有没有一种方法可以检查数据框中是否存在符合"列,如果没有,请添加该列?
is there a way to check if the "Met" column is present in the dataframe, and if not add it?
推荐答案
您按以下方式进行检查:
You check it like this:
if 'Met' not in df:
df['Met'] = df['freqC'] * df['coverage']
这篇关于 pandas :添加列(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文