Python为groupby求两次和

2024-04-25 18:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在对数据帧进行分组之后,我正在努力处理一个序列和,我希望有人能帮我想出一个主意。 基本上,我在下面的例子中,我需要有每个“材料”的总和。 基本上材料“ABC”应该给我2,和所有其他因为他们只有一个符号操作将有相同的值。你知道吗

import numpy as np
import pandas as pd

df = pd.DataFrame({ 
    "Material" : ["M-12", "H4-LAMPE", "M-12", "H4-LAMPE",
                  "ABC" , "H4-LAMPE", "ABC", "ABC"] , 
    "Quantity" : [6, 1, 3, 5, 1, 1, 10, 9],
    "TYPE": ["+", "-", "+", "-", "+", "-", "+", "-"]})
df.groupby(['Material', "Quantity"], as_index=False).count()

listX = []
for item in df["TYPE"]:
    if item == "+":
        listX.append(1)
    elif item == "-":
        listX.append(-1)
    else:
        pass
df["Sign"] = lista
df["MovementsQty"] = df["Quantity"]*df["Sign"]
#df = df.groupby(["Material", "TYPE", "Quantity1"]).sum()
df1 = df.groupby(["Material", "TYPE"]).sum()
df1.drop(columns=["Quantity", "Sign"], inplace=True)

print(df1)

结果是:

enter image description here

期望的结果是:

enter image description here

我试着再总结一遍,换个角度考虑,但到目前为止我还没有成功,我想我需要一些帮助。你知道吗

非常感谢你的帮助


Tags: importdfastypeitemh4quantitymaterial
3条回答

下面是另一个例子(相当类似于coldspeed)。你知道吗

#Correct quantity with negative sign (-) according to TYPE 
df.loc[df['TYPE'] == '-', 'Quantity'] *= -1

#Reconstruct df as sum of quantity to remove dups
df = df.groupby('Material')['Quantity'].sum().reset_index()
df['TYPE'] = np.where(df['Quantity'] < 0, '-', '+')

print(df)

退货:

   Material  Quantity TYPE
0       ABC         2    +
1  H4-LAMPE        -7    -
2      M-12         9    +

mapnumpy.sign

Quantity * TYPE加起来,然后算出符号。你知道吗

d = {'+': 1, '-': -1}
r = dict(map(reversed, d.items())).get
q = df.Quantity
m = df.Material
t = df.TYPE

s = pd.Series((q * t.map(d)).values, m, name='MovementsQty').sum(level=0)
s.reset_index().assign(TYPE=lambda x: [*map(r, np.sign(x.MovementsQty))])

   Material  MovementsQty TYPE
0      M-12             9    +
1  H4-LAMPE            -7    -
2       ABC             2    +

你在正确的轨道上。我试着改进你的代码。只需使用“Type”来确定和分配符号,使用np.where,执行groupbysum,然后根据结果重新计算“Type”列。你知道吗

v = (df.assign(Quantity=np.where(df.TYPE == '+', df.Quantity, -df.Quantity))
       .groupby('Material', as_index=False)[['Quantity']]
       .sum())

v.insert(1, 'Type', np.where(np.sign(v.Quantity) == 1, '+', '-'))

print (v)
   Material Type  Quantity
0       ABC    +         2
1  H4-LAMPE    -        -7
2      M-12    +         9

或者,您可以通过两个groupby调用来实现这一点:

i = df.query('TYPE == "+"').groupby('Material').Quantity.sum()
j = df.query('TYPE == "-"').groupby('Material').Quantity.sum()
# Find the union of the indexes.
idx = i.index.union(j.index)
# Reindex and subtract.
v = i.reindex(idx).fillna(0).sub(j.reindex(idx).fillna(0)).reset_index()
# Insert the Type column back into the result.
v.insert(1, 'Type', np.where(np.sign(v.Quantity) == 1, '+', '-'))

print(v)
   Material Type  Quantity
0       ABC    +       2.0
1  H4-LAMPE    -      -7.0
2      M-12    +       9.0

相关问题 更多 >