I have a dataframe:
>>> import pandas as pd
>>> dates = ['1/1/2020', '1/1/2020', '1/1/2020', '1/2/2020', '1/2/2020', '1/2/2020']
>>> humidity = [11, 22, 33, 44, 55, 66]
>>> hours = [0,16,24,0,16,24]
>>> df = pd.DataFrame(list(zip(dates, hours, humidity)),
... columns =['dates', 'hours', 'humidity'])
>>> df
dates hours humidity
0 1/1/2020 0 11
1 1/1/2020 16 22
2 1/1/2020 24 33
3 1/2/2020 0 44
4 1/2/2020 16 55
5 1/2/2020 24 66
I want to create two new columns. One column will store the index when hours == 16. Another column will store the index when humidity is maximum. Both these operations need to be done separately for each date. I can find the maximum humidity for each date using the groupby and transform functions as below:
>>> df["max_humidity"] = ""
>>> df["max_humidity"] = df["humidity"].groupby(df["dates"]).transform("max")
>>> df
dates hours humidity max_humidity
0 1/1/2020 0 11 33
1 1/1/2020 16 22 33
2 1/1/2020 24 33 33
3 1/2/2020 0 44 66
4 1/2/2020 16 55 66
5 1/2/2020 24 66 66
However, I couldn't figure out how to find the index position when the humidity is maximum for each date. The final result should look like this:
>>> df
dates hours humidity max_humidity sixteen_hr_idx max_humidity_idx
0 1/1/2020 0 11 33 1 2
1 1/1/2020 16 22 33 1 2
2 1/1/2020 24 33 33 1 2
3 1/2/2020 0 44 66 4 5
4 1/2/2020 16 55 66 4 5
5 1/2/2020 24 66 66 4 5