python - 如何将多列添加到 DataFrame?

标签 python pandas dataframe

我想向这个 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 个新列:

enter image description here

还有这段代码:

 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

关于python - 如何将多列添加到 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016451/

相关文章:

python - 如何将帮助打印到标准输出?

python - 这种方法是否为 "vectorized"- 用于中等数据集,速度相对较慢

python - 如何在 Google 文档字符串样式中格式化长行的参数描述

python - 检查鼠标是否在pygame窗口之外

python - 如何将带有 if 语句的嵌套 iterrows 转换为 Pandas 中的向量化函数或其他更快的方法

r - 如何用 mice R 仅估算一列或几列

r - 如何在R中的重复字符串中选择最长的ngram?

python - Pandas :合并(内部连接)数据框的行数比原来的多

python - Django - 我应该在生产环境中为管理用户设置 show_toolbar 吗?

python - 根据列表值从数据框中提取行的正确方法