python - 使用python pandas按名称计算多列

标签 python pandas numpy dataframe

我有一个类似这样的数据框,

cat_A  cat_B  cat_C  cat_D  dog_A  dog_B  dog_C  dog_D
  3      2      4      1      9      8      10     6
 ...
 ...

我知道如何使用列名在列之间进行计算,例如

df['ratio_A'] = df['cat_A']/df['dog_A']

cat_A  cat_B  cat_C  cat_D  dog_A  dog_B  dog_C  dog_D  ratio_A
  3      2      4      1      9      8      10     6      3/9

但是,当我尝试通过计算每一列来生成多列时,是否还有其他更简单的方法来计算所有列并一次性追加新列?而不是

df['ratio_B'] = df['cat_B']/df['dog_B']

df['ratio_C'] = df['cat_C']/df['dog_C']

df['ratio_D'] = df['cat_D']/df['dog_D']

当列长度变得非常大时,复制和粘贴会产生很多冗长的代码。 我是否需要创建 2 个列表,例如,

l1 = [cat_A, cat_B, cat_C, cat_D], l2= [dog_A, dog_B, dog_C, dog_D]

然后用for循环来实现?

最佳答案

IMO 此处的一个好做法是使用 MultiIndexes 而不是平面列:

df.columns = pd.MultiIndex.from_tuples(map(tuple, df.columns.str.split('_')))
df
  cat          dog          
    A  B  C  D   A  B   C  D
0   3  2  4  1   9  8  10  6

此时,计算比率是非常简单的礼貌索引对齐。

df['cat'] / df['dog']
          A     B    C         D
0  0.333333  0.25  0.4  0.166667

res =  df['cat'] / df['dog']
res.columns = pd.MultiIndex.from_product([['ratio'], res.columns])

pd.concat([df, res], axis=1)
  cat          dog               ratio                     
    A  B  C  D   A  B   C  D         A     B    C         D
0   3  2  4  1   9  8  10  6  0.333333  0.25  0.4  0.166667

关于python - 使用python pandas按名称计算多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741769/

相关文章:

Python 将日期时间设置为 UTC 时区

pandas - python - 在python中连接两个df时,为什么会丢失有关使用np.hstack的索引和列标题信息?

python - 计算 Pandas 数据框中的相同日期

python - 如何生成一天的时间戳?

python - 通过 Numpy/Pandas 使用 (n x 1) 数据创建一个 n x m 多项式数组

python - 从欧洲议会网站抓取数据时出现东欧字符问题

Python - Pandas 数据框 - 生成包含组级信息的列

python - 使用 Python 和 pyserial 访问 USB 串口

numpy - 如何在 Python 3.3 的 numpy 中启用 nditer 中的 REFS_OK 标志?

python - 使用分类数据构造稀疏矩阵