I have two diferent data frames. The first one is a catalog of diferent requests type and how many request i had at the moment.
data = {'Req Type': ['A', 'B', 'C', 'D'],'Req No': [20, 21, 19, 18]}
df1 = pd.DataFrame(data)
print(df1)
Req Type Req No
0 A 20
1 B 21
2 C 19
3 D 18
The other one is a data frame of how many new request i have this month.
data2 = {'Req Type': ['A', 'A', 'C', 'B']}
df2 = pd.DataFrame(data2)
print(df2)
Req Type
0 A
1 A
2 C
3 B
I need to create a dynamic index in my df2 that can detect what was the last number of each request type and start to sum. Example: The last number of A was “20”, so the index to req type “A” is “21”, then “22” and that for all my req type.
Req Type Index
0 A 21
1 A 22
2 C 20
3 B 22
Amaury Pedraza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
You can use a dictionary and update it in a single pass:
import pandas as pd
def get_indices(A, B):
res, TN = [], dict(zip(A['Req Type'], A['Req No']))
for t in B['Req Type']:
TN[t] += 1
res += [TN[t]]
B['Index'] = res
return B
A = pd.DataFrame({'Req Type': ['A', 'B', 'C', 'D'], 'Req No': [20, 21, 19, 18]})
B = pd.DataFrame({'Req Type': ['A', 'A', 'C', 'B']})
print(get_indices(A, B))
Prints
Req Type Index
0 A 21
1 A 22
2 C 20
3 B 22