Skip to main content
 首页 » 编程设计

python之如何将多列添加到 DataFrame

2025年05月04日20artech

我想向这个 DataFrame 添加总字段:

df_test = pd.DataFrame([ 
    {'id':1,'cat1a':3,'cat1b':2, 'cat2a':4,'cat2b':3}, 
    {'id':2,'cat1a':7,'cat1b':5, 'cat2a':9,'cat2b':6} 
]) 

这段代码几乎可以工作:

 def add_total(therecord): 
        t1 = therecord['cat1a'] + therecord['cat1b'] 
        t2 = therecord['cat2a'] + therecord['cat2b'] 
        return t1, t2 
 
df_test['cat1tot', 'cat2tot'] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1) 

除非它只产生 1 个新列:

还有这段代码:

 def add_total(therecord): 
        t1 = therecord['cat1a'] + therecord['cat1b'] 
        t2 = therecord['cat2a'] + therecord['cat2b'] 
        return [t1, t2] 
 
df_test[['cat1tot', 'cat2tot']] = df_test[['cat1a', 'cat1b', 'cat2a', 'cat2b']].apply(add_total,axis=1) 

结果:KeyError: "['cat1tot' 'cat2tot'] not in index"

我试图通过以下方式解决这个问题:

my_cols_list=['cat1tot','cat2tot'] 
df_test.reindex(columns=[*df_test.columns.tolist(), *my_cols_list], fill_value=0) 

但这并没有解决问题。那我错过了什么?

请您参考如下方法:

通常不是使用df.apply 是个好主意,除非您绝对必须这样做。原因是这些操作不是向量化的,即在后台有一个循环,其中每一行作为它自己的 pd.Series 被送入一个函数。

这将是一个向量化的实现:

df_test['cat1tot'] = df_test['cat1a'] + df_test['cat1b'] 
df_test['cat2tot'] = df_test['cat2a'] + df_test['cat2b'] 
 
#    cat1a  cat1b  cat2a  cat2b  id  cat1tot  cat2tot 
# 0      3      2      4      3   1        5        7 
# 1      7      5      9      6   2       12       15