airbnb_data_preprocessing.py 7.8 KB
Newer Older
J
jrzaurin 已提交
1 2
# coding: utf-8
import os
3 4
import warnings
from pathlib import Path
J
jrzaurin 已提交
5 6 7
from functools import reduce
from itertools import chain
from collections import Counter
8 9 10 11

import numpy as np
import pandas as pd
import gender_guesser.detector as gender
12
from sklearn.preprocessing import MultiLabelBinarizer
J
jrzaurin 已提交
13

J
jrzaurin 已提交
14
warnings.filterwarnings("ignore")
J
jrzaurin 已提交
15

J
jrzaurin 已提交
16 17
DATA_PATH = Path("data/airbnb")
fname = "listings.csv.gz"
J
jrzaurin 已提交
18 19 20
if not os.path.exists(DATA_PATH):
    os.makedirs(DATA_PATH)

J
jrzaurin 已提交
21
df_original = pd.read_csv(DATA_PATH / fname)
J
jrzaurin 已提交
22 23 24 25
print(df_original.shape)
df_original.head()

# this is just subjective. One can choose some other columns
J
jrzaurin 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
keep_cols = [
    "id",
    "host_id",
    "description",
    "house_rules",
    "host_name",
    "host_listings_count",
    "host_identity_verified",
    "neighbourhood_cleansed",
    "latitude",
    "longitude",
    "is_location_exact",
    "property_type",
    "room_type",
    "accommodates",
    "bathrooms",
    "bedrooms",
    "beds",
    "amenities",
    "price",
    "security_deposit",
    "cleaning_fee",
    "guests_included",
    "extra_people",
    "minimum_nights",
    "instant_bookable",
    "cancellation_policy",
    "reviews_per_month",
]
J
jrzaurin 已提交
55 56 57

df = df_original[keep_cols]
df = df[~df.reviews_per_month.isna()]
J
jrzaurin 已提交
58
df = df[~df.description.isna()]
J
jrzaurin 已提交
59 60 61 62 63 64 65 66 67 68
df = df[~df.host_listings_count.isna()]
print(df.shape)

# This is a preprocessing stage before preparing the data to be passed to WideDeep
# Let's go "column by column"

# house rules
#
# I will simply include a binary column with 1/0 if the property has/has not
# house rules.
J
jrzaurin 已提交
69
df["has_house_rules"] = df["house_rules"]
J
jrzaurin 已提交
70
df.has_house_rules.fillna(0, inplace=True)
J
jrzaurin 已提交
71 72
df["has_house_rules"][df.has_house_rules != 0] = 1
df.drop("house_rules", axis=1, inplace=True)
J
jrzaurin 已提交
73 74 75 76 77 78 79 80

# host_name
#
# I will use names to infer gender using `gender_guesser`

host_name = df.host_name.tolist()
d = gender.Detector()
host_gender = [d.get_gender(n) for n in host_name]
J
jrzaurin 已提交
81 82
replace_dict = {"mostly_male": "male", "mostly_female": "female", "andy": "unknown"}
host_gender = [replace_dict.get(item, item) for item in host_gender]
J
jrzaurin 已提交
83
Counter(host_gender)
J
jrzaurin 已提交
84 85
df["host_gender"] = host_gender
df.drop("host_name", axis=1, inplace=True)
J
jrzaurin 已提交
86 87 88 89 90 91 92
df.head()

# property_type, room_type, accommodates, bathrooms, bedrooms, beds and
# guests_included, host_listings_count, minimum_nights
#
# Here some standard pre-processing
df.property_type.value_counts()
J
jrzaurin 已提交
93 94 95 96 97 98
replace_prop_type = [
    val
    for val in df.property_type.unique().tolist()
    if val not in ["Apartment", "House"]
]
replace_prop_type = {k: "other" for k in replace_prop_type}
J
jrzaurin 已提交
99
df.property_type.replace(replace_prop_type, inplace=True)
J
jrzaurin 已提交
100
df["property_type"] = df.property_type.apply(lambda x: "_".join(x.split(" ")).lower())
J
jrzaurin 已提交
101 102

df.room_type.value_counts()
J
jrzaurin 已提交
103
df["room_type"] = df.room_type.apply(lambda x: "_".join(x.split(" ")).lower())
J
jrzaurin 已提交
104

J
jrzaurin 已提交
105 106
df["bathrooms"][(df.bathrooms.isna()) & (df.room_type == "private_room")] = 0
df["bathrooms"][(df.bathrooms.isna()) & (df.room_type == "entire_home/apt")] = 1
J
jrzaurin 已提交
107 108 109 110
df.bedrooms.fillna(1, inplace=True)
df.beds.fillna(1, inplace=True)

# Encode some as categorical
J
jrzaurin 已提交
111 112 113 114 115 116 117 118 119
categorical_cut = [
    ("accommodates", 3),
    ("guests_included", 3),
    ("minimum_nights", 3),
    ("host_listings_count", 3),
    ("bathrooms", 1.5),
    ("bedrooms", 3),
    ("beds", 3),
]
J
jrzaurin 已提交
120 121

for col, cut in categorical_cut:
J
jrzaurin 已提交
122 123
    new_colname = col + "_catg"
    df[new_colname] = df[col].apply(lambda x: cut if x >= cut else x)
J
jrzaurin 已提交
124 125 126 127 128 129
    df[new_colname] = df[new_colname].round().astype(int)

# Amenities
#
# I will just add a number of dummy columns with 1/0 if the property has/has
# not that particular amenity
J
jrzaurin 已提交
130 131 132 133 134 135 136 137 138
amenity_repls = (
    ('"', ""),
    ("{", ""),
    ("}", ""),
    (" / ", "_"),
    ("/", "_"),
    (" ", "_"),
    ("(s)", ""),
)
J
jrzaurin 已提交
139 140

amenities_raw = df.amenities.str.lower().tolist()
J
jrzaurin 已提交
141 142 143 144
amenities = [
    reduce(lambda a, kv: a.replace(*kv), amenity_repls, s).split(",")
    for s in amenities_raw
]
J
jrzaurin 已提交
145 146 147 148 149 150 151 152

all_amenities = list(chain(*amenities))
all_amenities_count = Counter(all_amenities)
all_amenities_count

# having a look to the list we see that one amenity is empty and two are
# "translation missing:..."
keep_amenities = []
J
jrzaurin 已提交
153 154
for k, v in all_amenities_count.items():
    if k and "missing" not in k:
J
jrzaurin 已提交
155 156
        keep_amenities.append(k)

J
jrzaurin 已提交
157 158 159 160
final_amenities = [
    [amenity for amenity in house_amenities if amenity in keep_amenities]
    for house_amenities in amenities
]
J
jrzaurin 已提交
161 162

# some properties have no amenities aparently
J
jrzaurin 已提交
163 164 165 166 167 168
final_amenities = [
    ["no amenities"] if not amenity else amenity for amenity in final_amenities
]
final_amenities = [
    ["amenity_" + amenity for amenity in amenities] for amenities in final_amenities
]
J
jrzaurin 已提交
169 170

# let's build the dummy df
J
jrzaurin 已提交
171 172
df_list_of_amenities = pd.DataFrame({"groups": final_amenities}, columns=["groups"])
s = df_list_of_amenities["groups"]
J
jrzaurin 已提交
173 174 175 176 177

mlb = MultiLabelBinarizer()

df_amenities = pd.DataFrame(mlb.fit_transform(s), columns=mlb.classes_, index=df.index)

J
jrzaurin 已提交
178
df.drop("amenities", axis=1, inplace=True)
J
jrzaurin 已提交
179 180 181 182 183
df = pd.concat([df, df_amenities], axis=1)
df.head()

# Price, security_deposit, cleaning_fee, extra_people

J
jrzaurin 已提交
184 185
money_columns = ["price", "security_deposit", "cleaning_fee", "extra_people"]
tmp_money_df = df[money_columns].fillna("$0")
J
jrzaurin 已提交
186 187 188 189

money_repls = (("$", ""), (",", ""))
for col in money_columns:
    val_str = tmp_money_df[col].tolist()
J
jrzaurin 已提交
190 191 192 193 194 195
    val_num = [
        float(st)
        for st in [
            reduce(lambda a, kv: a.replace(*kv), money_repls, s) for s in val_str
        ]
    ]
J
jrzaurin 已提交
196 197
    tmp_money_df[col] = val_num

J
jrzaurin 已提交
198
high_price, high_deposit, high_cleaning_fee, high_extra_people = 1000, 2000, 200, 100
J
jrzaurin 已提交
199 200 201 202 203 204

high_price_count = (tmp_money_df.price >= high_price).sum()
high_deposit_count = (tmp_money_df.security_deposit >= high_deposit).sum()
high_cleaning_fee_count = (tmp_money_df.cleaning_fee >= high_cleaning_fee).sum()
high_extra_people_count = (tmp_money_df.extra_people >= high_extra_people).sum()

J
jrzaurin 已提交
205 206 207 208
print("properties with very high price: {}".format(high_price_count))
print("properties with very high security deposit: {}".format(high_deposit_count))
print("properties with very high cleaning fee: {}".format(high_cleaning_fee_count))
print("properties with very high extra people cost: {}".format(high_extra_people_count))
J
jrzaurin 已提交
209 210 211 212

# We will now just concat and we will drop high values later one
df.drop(money_columns, axis=1, inplace=True)
df = pd.concat([df, tmp_money_df], axis=1)
J
jrzaurin 已提交
213 214 215 216 217 218 219
df = df[
    (df.price < high_price)
    & (df.price != 0)
    & (df.security_deposit < high_deposit)
    & (df.cleaning_fee < high_cleaning_fee)
    & (df.extra_people < high_extra_people)
]
J
jrzaurin 已提交
220 221 222 223 224 225
df.head()
print(df.shape)

# let's make sure there are no nan left
has_nan = df.isnull().any(axis=0)
has_nan = [df.columns[i] for i in np.where(has_nan)[0]]
J
jrzaurin 已提交
226 227
if not has_nan:
    print("no NaN, all OK")
J
jrzaurin 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

# Computing a proxi for yield

# Yield is defined as price * occupancy rate. Occupancy rate can be calculated
# by multiplying ((reviews / review rate) * average length of stay), where
# review rate and average length of stay are normally taken as a factor based
# in some model.  For example, in the San Francisco model a review rate of 0.5
# is used to convert reviews to estimated bookings (i.e. we assume that only
# half of the guests will leave a review). An average length of stay of 3
# nights  multiplied by the estimated bookings over a period gives the
# occupancy rate. Therefore, in the expression I have used below, if you want
# to turn my implementation of 'yield' into a "proper" one under the San
# Francisco model assumptions simply multiply my yield by 6 (3 * (1/0.5)) or
# by 72 (3 * 2 * 12) if you prefer per year.

J
jrzaurin 已提交
243 244
df["yield"] = (df["price"] + df["cleaning_fee"]) * (df["reviews_per_month"])
df.drop(["price", "cleaning_fee", "reviews_per_month"], axis=1, inplace=True)
J
jrzaurin 已提交
245 246
# we will focus in cases with yield below 600 (we lose ~3% of the data).
# No real reason for this, simply removing some "outliers"
J
jrzaurin 已提交
247 248
df = df[df["yield"] <= 600]
df.to_csv(DATA_PATH / "listings_processed.csv", index=False)
J
jrzaurin 已提交
249
print("data preprocessed finished. Final shape: {}".format(df.shape))