假设我有两个农场A和B。每个星期都有不同的动物。如何获得每个农场当前的动物累计数量?
gensim
通过groupby,我可以从每个农场中获得积蓄:
+---+-----+--------+-----+--------+
| | A | Farm_A | B | Farm_B |
+---+-----+--------+-----+--------+
| 0 | dog | 1 | cat | 1 |
| 1 | cat | 0 | dog | 1 |
| 2 | cat | 0 | dog | 1 |
| 3 | cat | 1 | dog | 0 |
| 4 | dog | 1 | dog | 1 |
| 5 | dog | 0 | dog | 0 |
| 6 | dog | 1 | cat | 1 |
+---+-----+--------+-----+--------+
我的问题是,如何从农场A和B的每一行中获取动物的累积总数?
例如第3行: 农场A中的动物是猫,那么我想从行0、1、2、3和3中的A和B农场中得到的猫总和为2。
再次在第3行,农场B的动物是狗,那么我要从第0、1、2、3行= 3的两个农场得到的狗总数
这是我想要实现的:
df['A cumsum Farm_A'] = df.groupby(['A'])['Farm_A'].cumsum()
df['B cumsum Farm_B'] = df.groupby(['B'])['Farm_B'].cumsum()
+---+-----+--------+-----+--------+-----------------+-----------------+
| | A | Farm_A | B | Farm_B | A cumsum Farm_A | B cumsum Farm_B |
+---+-----+--------+-----+--------+-----------------+-----------------+
| 0 | dog | 1 | cat | 1 | 1 | 1 |
| 1 | cat | 0 | dog | 1 | 0 | 1 |
| 2 | cat | 0 | dog | 1 | 0 | 2 |
| 3 | cat | 1 | dog | 0 | 1 | 2 |
| 4 | dog | 1 | dog | 1 | 2 | 3 |
| 5 | dog | 0 | dog | 0 | 2 | 3 |
| 6 | dog | 1 | cat | 1 | 3 | 2 |
+---+-----+--------+-----+--------+-----------------+-----------------+
答案 0 :(得分:0)
可以创建最后两列与虚拟变量一起使用。这样,您就可以跨农场为每种动物创建一个cumsum
,然后可以lookup
为每一行获取适当的值。
import pandas as pd
res = pd.get_dummies(df, columns=['A', 'B'])
# Animals only count if dummy & exists, so need to multiply.
res = pd.concat([res.filter(like='A_').multiply(res.Farm_A, axis=0),
res.filter(like='B_').multiply(res.Farm_B, axis=0)],
axis=1)
# Cumsum per animal
res = res.groupby(res.columns.str.split('_').str[1], axis=1).apply(lambda x: x.sum(1).cumsum())
# cat dog
#0 1 1
#1 1 2
#2 1 3
#3 2 3
#4 2 5
#5 2 5
#6 3 6
# Lookup
df['A at both'] = res.lookup(df.index, df.A)
df['B at both'] = res.lookup(df.index, df.B)
A Farm_A B Farm_B A at both B at both
0 dog 1 cat 1 1 1
1 cat 0 dog 1 1 2
2 cat 0 dog 1 1 3
3 cat 1 dog 0 2 3
4 dog 1 dog 1 5 5
5 dog 0 dog 0 5 5
6 dog 1 cat 1 6 3