<jupyter_start><jupyter_text>Pandas<jupyter_code>import pandas as pd
from urllib import request
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmpdirname:
    # Define the remote file to retrieve
    remote_url = 'http://data.insideairbnb.com/greece/attica/athens/2021-12-23/visualisations/listings.csv'
    # Define the local filename to save data
    local_file = Path(tmpdirname) / 'listings.csv'
    # Download remote and save locally
    request.urlretrieve(remote_url, local_file)
    print('created temporary directory', tmpdirname)
    # read the airbnb NYC listings csv file
    airbnb = pd.read_csv(local_file)
airbnb
airbnb.head(10)
airbnb.tail()
# Results for a single column
airbnb['name']
# results for multiple columns
hosts = airbnb[['host_id', 'host_name']]
hosts.head()
# Show the data types for each column
airbnb.dtypes
airbnb['last_review'] = pd.to_datetime(airbnb['last_review'])
airbnb.dtypes
# extract the year from a datetime series
airbnb['year'] = airbnb['last_review'].dt.year

# to integer
airbnb['year'] = airbnb['year'].astype('UInt16')

airbnb['year'].head()
# Strip leading and trailing spaces from a string series

airbnb['name'] = airbnb['name'].str.strip()
airbnb['name'].head()

airbnb['name_lower'] = airbnb['name'].str.lower()
airbnb['name_lower'].head()
# calculate using two columns
airbnb['min_revenue'] = airbnb['minimum_nights'] * airbnb['price']
airbnb[['minimum_nights', 'price', 'min_revenue']].head()
# get the mean price
airbnb['price'].mean()
# get the median price
airbnb['price'].median()
# get the mean grouped by type of room
airbnb[['room_type', 'price']].groupby('room_type', as_index=False).mean()
# get the median grouped by type of room
airbnb[['room_type', 'price']].groupby('room_type', as_index=False).median()
# get the median grouped by type of room and year
airbnb[['room_type', 'year', 'price']].groupby(['room_type', 'year'], as_index=False).median()

# get all rows with price < 1000
airbnb_under_1000 = airbnb[airbnb['price'] < 1000]
airbnb_under_1000.head()
# get all rows with price < 1000 and year equal to 2020
airbnb_2019_under_1000 = airbnb[(airbnb['price'] < 1000) & (airbnb['year'] == 2020)]
airbnb_2019_under_1000.head()
# distribution of prices under $1000
ax = airbnb_under_1000['price'].plot.hist(bins=40)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup