iterate over dataframe with conditions

Viewed 35

Initially I have two dataframe:

Dataframe A:

  Column1   Column2
0   X-5       H4
1   X-3       H4
2   X-4       H5
3   X-5       H5
4   X-5       H-3
5   X-3       H-3
6   X-3       H-3
7   X-4       H-4
8   X-4       H-5
9   X-3       H-4
10  X-5       H-3
11  X-3       H-3
12  X-5       H-5
13  X-5       H-3

Dataframe 2:

  Column1   Hours
0   X-5      12
1   X-4      14
2   X-3      10

I would like to be able to join the two dataframes into a single one when the condition of "Column1" is met, in addition to being able to eliminate the repeated rows and count the times they are repeated:

Column1 Column2 Repeat  Hours
0   H3    X-3      3    14
1   H-3   X-5      3    12
2   H-4   X-3      2    14
3   H-4   X-4      1    10
4   H-4   X-5      1    12
5   H-5   X-4      2    10
6   H-5   X-5      2    12

I would appreciate it if you would help me since I do not know very well how to do it. Thanks in advance

1 Answers

Is this what you want?

a.Column2 = a.Column2.str.replace("H(\d)", "H-\\1", regex=True)
pd.merge(a, b, on="Column1").groupby(["Column2", "Column1"], as_index=False).agg(
    Repeat=("Hours", "size"), Hours=("Hours", "first")
)
#   Column2 Column1  Repeat  Hours
# 0     H-3     X-3       3     10
# 1     H-3     X-5       3     12
# 2     H-4     X-3       2     10
# 3     H-4     X-4       1     14
# 4     H-4     X-5       1     12
# 5     H-5     X-4       2     14
# 6     H-5     X-5       2     12
Related