根据索引将一个数据帧除以另一个数据帧 [英] Divide a dataframe by another dataframe according to index

查看:48
本文介绍了根据索引将一个数据帧除以另一个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个数据帧的行除以另一个数据帧中的相同索引行.每个数据框中的列数相同.

I am trying to divide rows of a dataframe by the same index row in another dataframe. There are the same amount of columns in each dataframe.

目标是将一个列列表除以另一个列列表.有没有办法在 Pandas 中做到这一点?

The goal is to divide a list of columns by another list of columns. Is there a way to do this in Pandas?

这是一个示例数据:

import pandas as pd
import numpy as np
data1 = {"a":[10.,20.,30.,40.,50.],
         "b":[900.,800.,700.,600.,500.],
         "c":[2.,4.,6.,8.,10.]}
data2 = {"f":[1.,2.,3.,4.],
         "g":[900.,800.,700.,600.],
         "h":[10.,20.,30.,40.]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2) 

预期输出:

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2
4   NaN  NaN  NaN

截至目前,我正在使用我写的这个小函数:

As of now, I am using this little function I wrote:

def divDF(df1, df2):
    nRow, nCol = df1.shape
    result = pd.DataFrame(np.empty((nRow, nCol)), index=df1.index)
    for col in range(nCol):
        result.iloc[:,col] = df1.iloc[:,col] / df2.iloc[:,col]
    return result

这是唯一的方法还是有更快的方法?

Is this the only way or is there a faster way of doing this?

推荐答案

Pandas 会进行内在的数据对齐,因此如果您在两个 datafames 中将行索引和列标记为相同,Pandas 将按预期执行操作.

Pandas does intrinsic data alignment, so if you label your row index and column the same in both datafames, Pandas will perform the operation as expected.

您需要将列重命名为通用名称,并使用字典将旧列名称映射到新名称,如下所示:

You need rename your columns to a common name with dictionary mapping old column name to new name as follows:

rn_df1 = dict(list(zip(df1.columns.values,(df1.columns+'/'+df2.columns))))
rn_df2 = dict(list(zip(df2.columns.values,(df1.columns+'/'+df2.columns))))
df1.rename(columns=rn_df1).div(df2.rename(columns=rn_df2))

输出:

    a/f  b/g  c/h
0  10.0  1.0  0.2
1  10.0  1.0  0.2
2  10.0  1.0  0.2
3  10.0  1.0  0.2

这篇关于根据索引将一个数据帧除以另一个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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