使用python pandas按名称计算多列 [英] Calculate multiple columns by names using python pandas

查看:432
本文介绍了使用python pandas按名称计算多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的数据框,

I have a dataframe similar like this,

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

我知道如何通过使用列名(例如

I knew how to calculate between columns by using column names, like

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

但是当我尝试通过计算每个列来生成多个列时,还有其他更简便的方法来计算所有列并一次附加新列吗?代替

But when I tried to generate multiple columns by calculate each of those columns, are there any other easier ways to calculate all columns and append new columns by once? Instead of

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个类似的列表,

When the column length become very large it will be a lot of lengthy code to copy and paste. Do I need to create 2 lists like,

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

然后使用for循环来实现吗?

Then using for loops to implement?

推荐答案

IMO在这里,一个好的做法是使用MultiIndex es而不是平面列:

IMO a good practice here would be to work with MultiIndexes instead of flat columns:

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

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

At this point, computing the ratio is very simple courtesy index alignment.

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 pandas按名称计算多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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