使用 Pandas 数据框时,如果不存在,如何添加列? [英] When using a pandas dataframe, how do I add column if does not exist?

查看:45
本文介绍了使用 Pandas 数据框时,如果不存在,如何添加列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 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'] 

有没有办法检查Met"是否存在?列存在于数据框中,如果没有添加?

is there a way to check if the "Met" column is present in the dataframe, and if not add it?

推荐答案

你可以这样检查:

if 'Met' not in df:
    df['Met'] = df['freqC'] * df['coverage'] 

这篇关于使用 Pandas 数据框时,如果不存在,如何添加列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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