python - 根据索引将数据帧除以另一个数据帧

标签 python pandas

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

目标是将一个列列表除以另一个列列表。 有没有办法在 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

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

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

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

最佳答案

除以值以绕过索引对齐

dfd = df1.div(df2.values)
dfd.columns = df1.columns + '/' + df2.columns

dfd

    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

或者

c = df1.columns + '/' + df2.columns
pd.DataFrame(df1.values / df2.values, df1.index, c)

    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

@ScottBoston 的回答重生

c = df1.columns + '/' + df2.columns
d1 = dict(zip(df1.columns, c))
d2 = dict(zip(df2.columns, c))
df1.rename(columns=d1) / df2.rename(columns=d2)

    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

关于python - 根据索引将数据帧除以另一个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44466121/

相关文章:

python - 如何将 joblib 转储保存到另一个文件夹?

python - 将十进制时间戳转换为日期时间时如何保留微秒?

python - Pandas :TypeError:无法散列的类型: 'list'

python - 使用 Pandas value_counts() 添加 'rest' 组

Python 命名实体识别 (NER) : Replace named entities with labels

python - Cython 编译将文本附加到文件名,如何摆脱它?

python - Pandas DataFrame : Groupby Column, 按日期时间排序,并按条件截断组

python - For循环根据指定值排除一些DataFrame行

python - apply.pd.to_date_Time。申请取消映射/处理 NaT

python - 如何在 python 中将超大数与超小数相乘?