基于其他列和先前值填充列

时间:2018-06-11 10:02:43

标签: python pandas

我有一个包含用户,visit_types(预订或搜索)和酒店的数据库。我需要填写一个新栏目,其中包含预订最多的酒店,基于此行预订的酒店。

例如,

   **user**   **visit_type**   **hotel_code**   **most_booked**
1    user1       search             1                NaN
2    user1       search             2                NaN
3    user1       booking            1                NaN
4    user1       search             8                NaN
5    user1       booking            8                1
6    user2       search             6                NaN
7    user2       booking            6                NaN
8    user2       search             4                NaN
9    user2       booking            4                6
10   user2       booking            6                4
11   user2       booking            4                6

所以这个例子:

对于user1,预订最多的酒店将是,在第3行hotel = NaN,因为之前没有预订酒店,第5行将是hotel = 1.

对于user2,第7行是hotel = NaN,第9行是hotel = 6,第10行是hotel = 4(因为它是最后一次预订,只预订了两家酒店),最后一行是11,酒店将是6,因为它是最多预订到那一点(没有考虑第11行)。

1 个答案:

答案 0 :(得分:2)

这应该达到你想要的效果:

master

import pandas as pd
import operator
from collections import defaultdict

d = {      "user":["user1","user1","user1","user1","user1","user2","user2","user2","user2","user2","user2"],
     "visit_type":["search","search","booking","search","booking","search","booking","search","booking","booking","booking"],
     "hotel_code":[1,2,1,8,8,6,6,4,4,6,4]}

df = pd.DataFrame(data=d)
#Setting default value
df['most_booked']='NaN'

for user in df.user.unique():
    #Ignoring searches, only considering bookings
    df_bookings = df.loc[(df["visit_type"] == "booking") & (df['user'] == user)]
    last_booked = ""
    booking_counts = defaultdict(int)

    for i, entry in df_bookings.iterrows():
        #Skipping first booking
        if last_booked != "":
            highest = max(booking_counts.values())
            #Prefers last booked if it equals max
            if booking_counts[last_booked] == highest:
                max_booked = last_booked
            #Otherwise chooses max
            else:
                max_booked = max(booking_counts.items(), key=operator.itemgetter(1))[0]
            df.loc[i, 'most_booked'] = max_booked

        #Update number of bookings in dictionary
        current_booking = entry["hotel_code"]
        booking_counts[current_booking] += 1
        last_booked = current_booking