根据条件将数据框中的连续列相互划分

问题描述 投票:0回答:1

我偶尔使用Python,但不太擅长。我遇到了以下问题,我确信这个问题很容易解决...假设我们有以下“df_initial”数据帧作为输入。

enter image description here

我创建了以下数据透视表:

df_pivot = df_initial.pivot_table(index='Product', columns=['type'],
                                  aggfunc=np.sum)

enter image description here

我想计算每个产品在每个位置 1, 2, 3, ..., 6 的实际/目标比率,附加条件是如果不可能进行除法(对于任何行),则该比率应设置为 100%其中“目标”列中的值等于零)。

ratio_df = pd.DataFrame(index=df_pivot.index)

我定义了以下函数:

def division(a, b):
    if b == 0:
        return 1
    else:
        return a/b

然后我尝试应用该功能:

for col in df_pivot.columns:
    if col[1] == 'objective':
        continue
    ratio_df[col[0]] = division (df_pivot[(col[0], 'actual')] , df_pivot[(col[0], 'objective')])

返回:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我明白为什么这不起作用,但我不知道如何正确编写脚本。

我期待这样的桌子:

enter image description here

我尝试将功能更改为:

def division(a, b):
    if b.values[0] == 0:
        return 1
    else:
        return a / b.values[0]

然后:

ratio_df[col[0]] = df_pivot[col].apply(division, b=df_pivot.loc[:, (col[0], 'objective')])

但这不会产生正确的输出。

python pandas valueerror
1个回答
0
投票

用途:

df1 = df_initial.groupby(['type', 'Product']).sum()

out = df1.xs('actual').div(df1.xs('objective')).replace(np.inf, 1).mul(100)
© www.soinside.com 2019 - 2024. All rights reserved.