02099 Election Results
# Import your libraries
import pandas as pd
# Start writing code
voting_results.head() #voter / candidate
#boolean indexing - filtering voters who didn't vote
voting_results = voting_results[~voting_results['candidate'].isna()] #boolean indexing(condiiton included)
#voting_results = voting_results.dropna()
#voter rate
voting_results['voter_rate'] = voting_results['voter'].apply(lambda x : 1 / (voting_results['voter'] == x).sum())
result = voting_results.groupby('candidate')['voter_rate'].sum()
#print(result)
result = result.reset_index() #index(new numbers), originial index -> new column
# print(result)
result[result['voter_rate'] == result['voter_rate'].max()] #row
result[result['voter_rate'] == result['voter_rate'].max()]['candidate'] #final ans
๐ฅ
Q. ๊ฐ voter๊ฐ candidate์๊ฒ ํฌํ ์งํ. ์ด ๋, ์ด๋ค voter๋ ์ฌ๋ฌ ๋ช ์ candidate์๊ฒ ํฌํํ์๊ณ , ๋๋ช ์๊ฒ ํฌํํ๋ฉด, ๊ฐ candidate์ 1ํ๊ฐ ์๋ 0.5ํ๋ฅผ ๋๋ ๊ฐ์ง. ์ต๊ณ ๋ํ candidate ์ถ๋ ฅํ๊ธฐ
โ ์ด๋ค voter๋ candidate ํฌํ๋ฅผ ํ์ง ์์์(null ์ฒ๋ฆฌ ํ์)
โ ๋ ๋ช ์ด์์๊ฒ ํฌํ ์ ๊ฐ candidate์๊ฒ ๊ทธ๋งํผ ๋๋ ๊ฐ์ง ํฌํ์ ๋ถ์ฌ
* ์ฒซ๋ฒ์งธ โ ํด๊ฒฐ: boolean indexing์ผ๋ก ~voting_results['candidate'].isna()์ธ ์กฐ๊ฑด์ indexing์ผ๋ก ๋ฃ์ด, null์ด ์๋ ํ๋ง filtering. ๋๋ dropna()๋ก ํ ๋ฐฉ์๋ ๊ฐ๋ฅ
* ๋๋ฒ์งธ โ ํด๊ฒฐ: ์๋ก์ด voter_rate ์นผ๋ผ์ ๋ง๋ค๊ณ , ๊ฐ ํ ๋ณ apply() ํจ์ ์ ์ฉ. ๋ง๋ค ํจ์๋ lambda๋ฅผ ์ฌ์ฉํด lambda x : 1 / (voting_results['voter'] == x).sum()) ๋ด์ฉ ์ ์ฉ. voting_results['voter'] == xํ๋ฉด, ๊ฐ voter๊ฐ 2๊ฐ ์ด์์ผ ๊ฒฝ์ฐ, ๊ทธ๋งํผ True๊ฐ ์๊น. True๋ 1์ด๊ณ , False๋ 0์ด๋ฏ๋ก, sum()์ ์ ์ฉํด, ๊ฐ row๋ณ ํด๋น voter๊ฐ ๋ช ๋ช ์ธ์ง ์ ์ ์์. ์ด ๋, ๋์ผ ์ด๋ฆ(ex Sally)์ด 3๋ช ์๋ค๋ฉด, Sally์ ๋ํ rate์ 1์ด ์๋ 1/3์ด ๋๋ค. ์ฆ, 1 / (voting_results['voter'] == x).sum()) ์ ์ฉํจ์ผ๋ก์จ ๊ฐ row์ voter rate ์ ์ ์๋ค.
* groupby() ์ ์ฉํด ๊ฐ candidate๋ณ voter_rate ํฉ ๊ตฌํ๊ธฐ(groupby๋ ๋ค์ aggregation ํจ์ ํ์ ์ ์ฉ)
* reset_index() ์ ์ฉํด candidate์ index๊ฐ ์๋ ์๋ก์ด column์ผ๋ก ๋ณ๊ฒฝ
* boolean indexing์ผ๋ก ์ต๋๊ฐ voter_rate์ธ candidate ๊ตฌํ๋ฉด ๋!
10060 Top Cool Votes
# Import your libraries
import pandas as pd
# Start writing code
yelp_reviews.head()
#boolean indexing
res = yelp_reviews[yelp_reviews['cool'] == yelp_reviews['cool'].max()]
#shown in dataframe along with selected columns
res[['business_name', 'review_text']]
๐ฅ Q. ๊ฐ์ฅ ๋์ cool votes ๋ฐ์ ํ(more or equal than 1)์ busines_name๊ณผ review_text ๋ ํ์ ๋ชจ์ dataframe ํํ๋ก ์ถ๋ ฅ
* ๋ ๊ฐ ์ด์์ selected rows๋ฅผ dataframe ํํ๋ก ๋ง๋ค์ด์ ์ถ๋ ฅํ๋ ค๋ฉด res[['business_name', 'review_text']]์ ๊ฐ์ด dataframe_name[[]]์ผ๋ก [] ์์ []์ ๋ ๋ฃ๊ณ , column names ๋์ด.
10353 Workers With The Highest Salaries
# Import your libraries
import pandas as pd
# Start writing code
worker.head()
#inner-merge based on the same column 'id'
worker_merged = worker.merge(title, how = 'inner', left_on = 'worker_id' , right_on = 'worker_ref_id')
#inner-merge: show only intersected rows
#boolean indexing
worker_merged[worker_merged['salary'] == worker_merged['salary'].max()]['worker_title']
๐ฅ ๊ฐ์ฅ ๋์ Salary๋ฅผ ๋ฐ๋ worker_title ๊ตฌํ๊ธฐ
* ๋ฌธ์ ๋ ๊ฐ๋จํ๋, ํ ์ด๋ธ์ด ๋ ๊ฐ์ด๋ฏ๋ก merge ํ์. worker.merge(title, how = 'inner', left_on = 'worker_id' , right_on = 'worker_ref_id') ์ฝ๋๋ฅผ ์ฌ์ฉํด worker_id์ worker_ref_id ๊ณตํต ์นผ๋ผ์ผ๋ก, ๋์ผ id๊ฐ ์กด์ฌํ๋ ํ์ผ๋ก๋ง merge(inner-merge) ์งํ(left_on๊ณผ right_on์ผ๋ก ๊ฐ ํ ์ด๋ธ์ key column ๋ช ์ง์ ๊ฐ๋ฅ)
* boolean indexing์ผ๋ก salary ์ต๋๊ฐ์ธ ๊ฒฝ์ฐ์๋ง worker_title ๊ตฌํ๊ธฐ
02102 Flags per Video
# Import your libraries
import pandas as pd
# Start writing code
user_flags.head()
user_flags = user_flags[user_flags['flag_id'].notnull()]
user_flags['name'] = user_flags['user_firstname'].astype(str) + ' ' + user_flags['user_lastname'].astype(str)
answer = user_flags.groupby(by='video_id')['name'].nunique().reset_index()
๐ฅ ๊ฐ ๋น๋์ค ๋ณ๋ก ์ค๋ณต ์ ์ธํ ์ด๋ฆ๋ณ ์ฌ์ฉ์ ๋ช ๋ช ์ธ์ง ์ ๋ฆฌํด์ ์ถ๋ ฅํ๋ ๋ฌธ์
(1) ๋จผ์ null ๊ฐ ์ ๊ฑฐ
(2) name ์ด ๋ง๋ค ๋ firstname๊ณผ lastname ํฉ์ณ์ ๋ง๋ค๊ธฐ. ์ด ๋, astype(str) ํจ์ ํ์ฉํด์ ๊ฐ ์ด์ ๋ฌธ์์ด๋ก ๋ฐ๊ฟ์ ํฉ์น ๋ค name ์ด ๋ด์ฉ ์์ฑ
(3) ์ฃผ์ด์ง user_flags ๋ฐ์ดํฐ ํ๋ ์์ video_id๋ก groupby ์งํํ๊ณ ๊ฐ name๋ณ nunique() ํจ์ ์ฌ์ฉํด ์ค์ video ๋ณ ์ธ์ ์ ์ ๋ฆฌํด์ ์ถ๋ ฅ. ์ด ๋, groupby ์งํํ์ผ๋ฏ๋ก reset_index() ํ์
02005 Share of Active Users
# Import your libraries
import pandas as pd
# Start writing code
fb_active_users.head()
df = fb_active_users[fb_active_users['status'] == 'open']
df_us = df[df['country'] == 'USA']
output = df_us.shape[0] * 100/ fb_active_users.shape[0]
๐ฅ ์กฐ๊ฑด์ ๋ง๋ ํ ํํฐ๋ง ์งํ ํ, ์ ์ฒด ํ ๋๋น ์กฐ๊ฑด์ ๋ง๋ ํ์ ๊ฐ์์ธ ๋น์จ ์ถ๋ ฅ
09610 Find Students At Median Writing
# Import your libraries
import pandas as pd
# Start writing code
sat_scores.head()
sat_scores[sat_scores['sat_writing'] == sat_scores['sat_writing'].median()]['student_id']
#sat_scores['sat_writing'].quantile(0.25)
๐ฅ sat_writing์ด median ๊ฐ์ ํด๋นํ๋ ๋ฐ์ดํฐ์ student_id ์ถ๋ ฅํ๊ธฐ
: median() ํจ์ ๋ฐ๋ก ์งํ. ์ฌ๋ถ์ ์ ๊ธฐ์ค P1, P3๋ผ๋ฉด quantile(0.25), quantile(0.75) ํ์ฉ
09650 Top 10 Songs 2010
# Import your libraries
import pandas as pd
# Start writing code
billboard_top_100_year_end.head()
billboard_top_100_year_end = billboard_top_100_year_end[(billboard_top_100_year_end['year'] == 2010) & (billboard_top_100_year_end['year_rank'].between(1, 10))]
billboard_top_100_year_end.sort_values(by='year_rank', ascending=True)
billboard_top_100_year_end[['year_rank', 'group_name', 'song_name']].drop_duplicates()
๐ฅ 2010๋ ๋น๋ณด๋ top 10์ ๋ชฉ๋ก ์ถ๋ ฅ. ๋จ, ๋ญํฌ ๊ธฐ์ค ์ค๋ฆ์ฐจ์ ์ถ๋ ฅํ๊ณ , ๋์ผ ๋ ธ๋ ์ค๋ณต ์ถ๋ ฅ ๊ธ์ง
(1) between(1,10)์ ํ์ฉํด rank์ 1์๋ถํฐ 10์๋ฅผ ํ๋ฒ์ ํํฐ๋ง ๊ฐ๋ฅ
(2) sort_values(by = 'year_rank', ascending = True)๋ก ํน์ ์ด ๊ธฐ์ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
(3) drop_duplicates() ํจ์ ํ์ฉํด ํน์ ๋ฐ์ดํฐ์ ์ค๋ณต ์ด๋ง ์ ๊ฑฐ ๊ฐ๋ฅ
10182 Number of Streets Per Zip Code
# Import your libraries
import pandas as pd
# Start writing code
sf_restaurant_health_violations.head()
sf_restaurant_health_violations['street_str']=sf_restaurant_health_violations['business_address'].str.split()
sf_restaurant_health_violations['street_str']=sf_restaurant_health_violations['street_str'].apply(lambda x: x[1].lower() if x[0].isnumeric() else x[0].lower())
sf_restaurant_health_violations_grouped = sf_restaurant_health_violations.groupby('business_postal_code')['street_str'].nunique().reset_index()
sf_restaurant_health_violations_grouped.sort_values(by=['street_str','business_postal_code'],ascending=[False,True])
๐ฅ street_str์์ street ์ด๋ฆ๋ง ์ถ์ถ. ์ด๋ฆ ์ถ์ถํ๊ณ , postal_code ๋ณ street ๊ฐ์ ์ถ์ถ. ์ดํ ๋ ์ด ๊ธฐ์ค์ ๋ฐ๋ผ ๋ด๋ฆผ/์ค๋ฆ์ฐจ์ ์ ๋ ฌ
(1) .str.split()์ผ๋ก ๋จผ์ ๋ฌธ์์ด๋ก ๋ณํ ๋ค split()์ผ๋ก ๊ฐ ๋น์นธ ๋ณ split
(2) apply(lambda) ํจ์ ์ ์ฉํด if x[0].isnumeric()์ผ ๊ฒฝ์ฐ x[1].lower() ์๋๋ฉด x[0].lower()๋ก street name ์ ํ
(3) groupby - nunique() - reset_index()
(4) sort_values()๋ก by ํ์ฉํด ๋ ์ด ๊ฐ๊ฐ ๋ด๋ฆผ/์ค๋ฆ์ฐจ์ ์ ๋ ฌ. ์ด ๋ by์ ascending ๊ฐ๊ฐ[]๋ก ๋ฃ์
10351 Activity Rank
# Import your libraries
import pandas as pd
# Start writing code
google_gmail_emails.head()
google_gmail_emails = google_gmail_emails.groupby('from_user').size().reset_index(name='total_emails').sort_values(by=['total_emails','from_user'],ascending=[False,True])
google_gmail_emails['Rank'] = range(1, len(google_gmail_emails) + 1)
#google_gmail_emails['rank'] = google_gmail_emails['total_emails'].rank(method='first', ascending=False)
google_gmail_emails
๐ฅ ๊ฐ์ฅ ๋ง์ ์ด๋ฉ์ผ ๋ณด๋ธ ์์ผ๋ก ์ ๋ ฌ(๋๊ฐ์ง ์ด์ ๊ธฐ์ค)ํ๊ณ , rank ์ด ๋ง๋ค๊ธฐ
(1) groupby์์ size()๋ก ๊ฐ group ๋ด์ ์ด ๊ฐ์๋ก grouping ๊ฐ๋ฅ - reset_index()์์ name ์ธ์๋ก size()๋ก grouping๋ ์๋ก์ด ๊ฐ ๊ทธ๋ฃน ๋ด์ ๊ฐ์ ์ด์ ์ด๋ฆ์ 'total_emails'๋ก ๋ง๋ค ์ ์๋ค.
(2) sort_values๋ก ๋ ๊ฐ์ง ์ด์์ ์ด ๊ธฐ์ค ์ ๋ ฌ
(3) ์๋ก์ด Rank ์ด ๋ง๋ค ๋ range(1, len(df) +1) ๋๋ .rank(method = 'first', ascendig = False)๋ก ๋ง๋ค ์ ์๋ค.
09915 Highest Cost Orders
# Import your libraries
import pandas as pd
# Start writing code
customers.head()
df = customers.merge(orders, how="inner", left_on="id", right_on="cust_id")
df = df[('2019-02-01' <= df['order_date']) & (df['order_date'] <= '2019-05-01')]
# df = df[df['order_date'].between('2019-02-01', '2019-05-01')]
df = df.groupby(['first_name','order_date'])['total_order_cost'].sum().reset_index(name='max_cost').sort_values('max_cost',ascending = False)
#df = df.groupby(['first_name','order_date'])['total_order_cost'].sum().to_frame('max_cost').reset_index().sort_values('max_cost',ascending = False)
res = df[df['max_cost'] == df['max_cost'].max()]
๐ฅ ์ฃผ์ด์ง ๊ธฐํ ๋ณ ๋ฐ์ดํฐ์์ ๊ฐ customer ๋ณ daily basis total_order_cost ์ต๊ณณ๊ฐ์ ์ฐ์ customer ์ ๋ณด ์ถ๋ ฅ
(1) ๋จผ์ between() ๋๋ ์ง์ ๋ถ๋ฑ์์ผ๋ก datetime ์ ํด์ง ๊ธฐํ๋ณ ๋ฐ์ดํฐ filtering
(2) groupby ๋ด์ ๋ ๊ฐ์ง ์ด์์ ์ด์ ๊ธฐ์ค์ผ๋ก ๋ฃ์ด grouping ๊ฐ๋ฅ. reset_index()์์ name ์ธ์๋ฅผ ๋ฃ์ด total_order_cost ํฉ๊ณ ์ด๋ฆ ๋ฐ์ดํฐ ์ด์ ์๋ก์ด ์ด ์ด๋ฆ์ผ๋ก ์ค์ ์ผ๋ก ๊ฐ๋ฅ. / ๋๋ reset_index()์์ name์ธ์๋ฅผ ์๋ฃ๊ณ , ์ด์ฐจํผ groupby()์ ๊ฒฐ๊ณผ๋ Series์ด๋ฏ๋ก to_frame()์ ์ ์ฉํด to_frame()์์ ์๋กญ๊ฒ ๋ง๋ค ์ด์ ์ด๋ฆ์ ๋ฃ์ผ๋ฉด ๋จ. to_frame()์ Series๋ฅผ Dataframe์ผ๋ก ๋ฐ๊พธ๋ ํจ์.
(3) boolean indexing์ผ๋ก ์ต๋๊ฐ filtering
02064 Difference Between Times
# Import your libraries
import pandas as pd
# Start writing code
marathon_male.head()
male=(abs(marathon_male['gun_time']-marathon_male['net_time'])).mean()
female=(abs(marathon_female['gun_time']-marathon_female['net_time'])).mean()
abs(female-male)
๐ฅ ๋ column ์ฌ์ด์ ์ฐจ์ด(์ ๋๊ฐ)์ ํ๊ท ์ ์ ์ฝ๋ ๋ ์ค๊ณผ ๊ฐ์ด ํ ๋ฐฉ์ ๊ตฌํ ์ ์๋ค.
(โ ) 02014 Hour With The Highest Order Volume
# Import your libraries
import pandas as pd
# Start writing code
postmates_orders.head()
postmates_orders["hour"] = postmates_orders[ "order_timestamp_utc" ].dt.hour
#.apply(lambda x: x.hour)
postmates_orders["date"] = postmates_orders["order_timestamp_utc"].dt.date
result = postmates_orders.groupby([postmates_orders['date'], postmates_orders['hour']])['id'].count().reset_index(name='n_orders')
result = result.groupby('hour')['n_orders'].mean().reset_index() #name x -> n_orders
result[result['n_orders'] == result['n_orders'].max()]
๐ฅ ์ด๋ค ๋ ์ ์ด๋ค ์๊ฐ์ด ๊ฐ์ฅ ๋ง์ order_volumn ํ๊ท ๊ฐ์ ๊ฐ์ง๋ ์ง ์์๋ณด๋ ๋ฌธ์
* (1) hour์ date ์นผ๋ผ์ ๋ง๋ค๊ณ (dt.hour์ dt.date ์ฌ์ฉ), date์ hour ์์๋๋ก groupby ์งํํด ๊ฐ ๋ ์ง์ ๊ฐ ์๊ฐ๋ณ ์ฃผ๋ฌธ ๊ฐ์ ๊ตฌํ๊ธฐ
(reset_index ์ธ์๋ก ()์์ ์๋กญ๊ฒ ๋ง๋ค์ด์ง๋ ์นผ๋ผ ์ด๋ฆ ๋ฃ๊ธฐ)
* (2) ๋ค์ hour๋ก grouping์ ์งํํด hour๋ณ ์ฃผ๋ฌธ๊ฐ์ ํ๊ท ์ ๊ตฌํ๊ธฐ
* (3) ์ต๋๊ฐ filtering
Q. groupby๋ฅผ ๋ ๋ฒ ์งํํ์ง ์๊ณ , ๋จผ์ ๊ฐ ์๊ฐ๋ณ๋ก groupingํ ์๋ ์์๊น?
A. 3/11์ผ 17์ order๊ฐ 3๊ฐ, 3/12์ผ 17์ order๊ฐ 1๊ฐ๋ผ๋ฉด, ์ ์ด์ hour๋ก๋ง groupingํ๋ฉด, count๋ 4๊ฐ ๋๋ค. ํ์ง๋ง, day๋ณ hour๋ณ average์ ์ต๋๊ฐ์ด๊ธฐ์, ์ฐ๋ฆฐ ๋จผ์ day๋ณ hour๋ณ grouping ์งํ ํ์. ๊ทธ๋ฌ๋ฉด 3/11์ผ 17์๋ 3, 3/12์ผ 17์๋ 1์ด ๋๊ณ , hour๋ก groupingํ๋ฉด ํ๊ท ๊ฐ์ธ 2๊ฐ ๋์จ๋ค. ๋ฐ๋ผ์, ์ค๋ณต ๋ฐ์ดํฐ๋ก ์ธํด groupby๋ฅผ ๋ ๋ฒ ์งํํด์ผ ํ๋ค๋ ์ ์ ๋งค์ฐ ์ฃผ์
02042 Employees' Years In Service
# Import your libraries
import pandas as pd
# Start writing code
uber_employees.head()
uber_employees['still_employed'] = uber_employees['termination_date'].apply(lambda x: 'yes' if pd.isna(x) else "no")
uber_employees['termination_date'] = uber_employees['termination_date'].fillna(pd.to_datetime('2021-05-01'))
uber_employees['years_worked'] = ((uber_employees['termination_date'] - uber_employees['hire_date']).dt.days)/365
result = uber_employees[uber_employees['years_worked'] > 2][['first_name', 'last_name', 'years_worked', 'still_employed']]
๐ฅ ๊ทผ๋ฌด๊ธฐ๊ฐ 2๋ ๋์ ๊ฒฝ์ฐ์ ์ฌ์๋ค์ด ํ์ฌ๋ employed๋์๋ ์ง ์์๋ณด๋ ๋ฌธ์
(1) ๋จผ์ lambda๋ฅผ ํ์ฉํด isna(x)๋ก yes๋ no ๋ฐ์ดํฐ ๋ฃ๋ apply() ํจ์ ์ ์ฉ
(2) fillna()๋ก null์ธ ๊ฒฝ์ฐ 2021-05-01์ ๋ฃ๋๋ฐ pd.to_datetime() ํ์ฉ. ๊ทธ๋ฆฌ๊ณ years_worked ๊ตฌํ๊ณ (dt.days/365) >2์ ๋ง๋ ๋ฐ์ดํฐ๋ง ๊ด๋ จ ๋ด์ฉ ์ถ๋ ฅ
02153 Average On-Time Order Value
# Import your libraries
import pandas as pd
# Start writing code
delivery_details.head()
delivery_details['duration_time_minute'] = (delivery_details['delivered_to_consumer_datetime'] - delivery_details['customer_placed_order_datetime']).dt.total_seconds()/60
delivery_details_under_45 = delivery_details[delivery_details['duration_time_minute'] <= 45]
delivery_filtered = delivery_details[delivery_details['driver_id'].isin(delivery_details_under_45['driver_id'].drop_duplicates())]
delivery_filtered.groupby('driver_id')['order_total'].mean().reset_index(name='avg_order_value')
๐ฅ ์ ์ํ duration time์ด 45๋ถ ์ดํ์ธ order๊ฐ ์ ์ด๋ ํ ๊ฐ ์๋ driver์ average order value ๊ตฌํ๊ธฐ.
โ ์ฃผ์์ ) duration time์ด 45๋ถ ์ดํ์ธ order๋ง ๋ชจ์์ average order value๋ฅผ ๊ตฌํ๋ ๊ฒ ์๋๋ผ, duration time์ด 45๋ถ ์ด๊ณผ์ธ order๊ฐ ์๋ driver๋ผ๋, driver์ order ์ค duration time์ด 45๋ถ ์ดํ์ธ order๊ฐ ์กด์ฌํ๋ค๋ฉด, ํด๋น driver์ 45๋ถ ์ด๊ณผ์ธ order๊น์ง ๋ชจ๋ ํฌํจํด์ average order value ๊ตฌํ๊ธฐ.
(1) duration time column ๋ง๋ค๊ธฐ(datetime - datetime ํ๋ฉด timedelta data type์ด ๋์ค๊ณ , total_seconds()/60์ ํ์ฉํด duration minute ๊ณ์ฐ ๊ฐ๋ฅ
(2) ๋ณ๋์ under_45 dataframe๋ง๋ค์ด์ ์๋กญ๊ฒ ๋ง๋ column์ด 45๋ถ ์ดํ์ผ ๋์ ์ ๋ณด๋ง ๋ชจ์ ๊ณณ์์์ driver_id ๊ตฌํ๊ธฐ.
(3) ๊ตฌํ driver_id์ drop_duplicates() ํจ์ ์จ์ ์ค๋ณต ์๋ driver id์ ๊ธฐ์กด driver_id๊ฐ ํฌํจ๋๋ ์ง ์ ๋๋ ์ง isin()์ผ๋ก ํ๋จ
(4) driver_id๊ฐ ํฌํจ๋๋ ๊ฒฝ์ฐ๋ง delivery_filtered๋ก ์ต์ข dataframe์ผ๋ก ํ๋จ.
(5) ๋ง์ง๋ง์ผ๋ก groupby ์งํํด์ mean()ํจ์๋ก avg_order_value ๊ตฌํ๊ธฐ.
โ ์๊ฐ ๊ด๋ จ data type) datetime๊ณผ timedelta 2๊ฐ ์ ํํ ๊ตฌ๋ถํ๊ธฐ
02113 Extremely Late Delivery
# Import your libraries
import pandas as pd
from datetime import timedelta
# Start writing code
delivery_orders.head()
delivery_orders = delivery_orders[delivery_orders['actual_delivery_time'].notnull()]
delivery_orders['is_extreme'] = (delivery_orders['actual_delivery_time'] > (delivery_orders['predicted_delivery_time'] + timedelta(minutes=20))).astype(int)
#delivery_orders['month'] = (delivery_orders['order_placed_time'].dt.month)
delivery_orders['month'] = delivery_orders['order_placed_time'].dt.to_period('M')
res = delivery_orders.groupby('month')['is_extreme'].agg(lambda x: x.mean()*100).reset_index(name='perc_extremely_delayed')
res
๐ฅ ๋ -์๋ณ extremely late orders์ ๋น์จ์ %๋ก ๋ํ๋ด๊ธฐ
(1) ๋จผ์ , extreme ์ฌ๋ถ column ์์ฑ) datetime + timedelta(duration time)๊ฐ ๊ฐ๋ฅํ๋ฉฐ, timedelta(minutes=20)๋ฅผ ์ฐ๊ธฐ ์ํด์๋ ์ง์ from datetime import timedelta ์ฌ์ฉ
(2) ์ด ๋, ๋ -์ ๊ฐ์ฒด๋ก ๋๋๊ธฐ ์ํด dt.to_period('M') ์ฌ์ฉ. to_period()๋ ๊ธฐ๊ฐ๋จ์์ ๊ฐ์ฒด๋ก ๋ณํ
โ dt.month๋ year ํฌํจํ์ง ์์ ๋ง ๊ทธ๋๋ก month ์์ฒด์ด๋ฏ๋ก yearํฌํจํด์ ์ถ๋ ฅ x
(3) ๊ธฐ๊ฐ๋จ์์ธ '์' ๋จ์์ ๊ฐ์ฒด๋ก ๋ฐ๊พผ ['month']๋ฅผ groupby๋ก ์งํํ๊ณ is_extreme์ ๊ฐ์ง๊ณ agg() ํจ์ ์งํํด x.mean()*100์ผ๋ก ์ค์ ํ๊ท ๊ฐ์ ๊ตฌํ ์ ์๋ค. (agg๋ง๊ณ apply๋ ์ ์ฉ ๊ฐ๋ฅ)
09601 Find the Best Day for Trading AAPL Stock
# Import your libraries
import pandas as pd
# Start writing code
aapl_historical_stock_price.head()
aapl_historical_stock_price['day_of_month'] = aapl_historical_stock_price['date'].dt.day
res1 = aapl_historical_stock_price.groupby('day_of_month')['open'].mean().reset_index()
res2 = aapl_historical_stock_price.groupby('day_of_month')['close'].mean().reset_index()
res = res1.merge(res2, how='inner', left_on = 'day_of_month', right_on = 'day_of_month')
res['diff'] = res['close']-res['open']
res[res['diff'] == res['diff'].max()][['day_of_month', 'open', 'close']]
๐ฅ ๊ฐ ์ ๋ณ ์ผ์ค, open๊ณผ close์ ์ฐจ์ด๊ฐ ๊ฐ์ฅ ํฐ ์ผ์ ์ถ๋ ฅํ๊ธฐ
* ์ฌ๊ธฐ์ ์ฃผ์์ ์, '์ผ'์ ์ ๋ด์ ๋ชจ๋ '์ผ'์ ๋ปํ๋ค. ๋ฐ๋ผ์, 3์ 1์ผ์ด๋ 4์ 1์ผ์ด๋ ๊ฐ์ 1์ผ๋ก ๊ฐ์ฃผ. ๋ฐ๋ผ์ .dt.day ์ฌ์ฉ ๊ฐ๋ฅ
09762 Find the Day of the Week that most People check-in
# Import your libraries
import pandas as pd
# Start writing code
airbnb_contacts.head()
airbnb_contacts['dayofweek'] = airbnb_contacts['ds_checkin'].dt.dayofweek
res = airbnb_contacts.groupby('dayofweek').size().reset_index(name='size')
res[res['size'] == res['size'].max()]
๐ฅ day-of-week๋ณ ๊ฐ์ฅ ๋ง์ ๋ฐฉ๋ฌธ ํ์ ๊ตฌํ๊ธฐ
(1) day-of-week์ dt.dayofweek ํ์ฉ
(2) groupby().size()๋ก ๊ฐ ๊ทธ๋ฃน๋ณ ๊ฐ์ size ๊ตฌํ๊ธฐ
02154 Top 2 Sales Time Combinations
def categorize_time(hour):
if hour < 12:
return 'Morning'
elif 12 <= hour <= 15:
return 'Early Afternoon'
else:
return 'Late Afternoon'
# Import your libraries
import pandas as pd
# Start writing code
sales_log.head()
sales_log['day_of_week'] = sales_log['timestamp'].dt.day_name()
sales_log['time_of_day'] = sales_log['timestamp'].dt.hour.apply(categorize_time)
res = sales_log.groupby(['day_of_week','time_of_day']).size().reset_index(name='total_orders')
top_orders = res['total_orders'].nlargest(2)
res[res['total_orders'].isin(top_orders)].sort_values(by='total_orders', ascending = False)
๐ฅ day_of_week ์ค time_of_day ์ค order์ ๊ฑด์ top 2(๊ฑด์ ์ค๋ณต์ด๋ฉด ๋ชจ๋ ํฌํจ) ์ ๋ณด ์ถ๋ ฅ
(1) ๋จผ์ day_of_week๋ฅผ datetime column์์ ๋ฝ์ ๊ฑด๋ฐ, 0~6 ์ซ์๊ฐ ์๋ Saturday, Friday์ ๊ฐ์ด ์์ผ ์ด๋ฆ์ผ๋ก ๋ฝ์๋ ค๋ฉด dt.day_name() ํ์ฉ
(2) time_of_day๋ apply() ํจ์๋ฅผ ๋ฐ๋ก ์ ์ฉํ์ฌ, ๋ณ๋์ ํจ์ categorize_time์์ ์ฌ๋ฌ ๋ถ๊ธฐ๋ฌธ์ผ๋ก ์ฒ๋ฆฌ
(3) groupby ๋ ์นผ๋ผ grouping ์งํ / ๊ฐ group๋ณ size ๊ฐ์์ด๋ฏ๋ก size() ์ ์ฉ
(4) ์ผ๋จ ์ค๋ณต ๋ฐ์ดํฐ ํฌํจ top ์์ ๋ฐ์ดํฐ ๊ณ ๋ฅด๋ ค๋ฉด nlargest(x)๋ก ๋ด์ฉ์ ๋ฝ๊ณ , isin() ํ์ฉํด ํด๋น ๋ชจ๋ ๋ด์ฉ ๊ฐ์ ธ์ค๊ธฐ
* ์ ๋ฌธ์ ํต์ฌ ์ฝ๋ ํค์๋ ์ ๋ฆฌ
(1) boolean indexing์ ํ์ฉํ ~isna()๋ก null data ํฌํจ ํ deletion
(2) apply() ํ์ฉํด lambda x : 1 / (voting_results['voter'] == x).sum()) ํจ์๋ก ๊ฐ data์ share ๊ตฌํ๊ธฐ
(3) groupby + aggregation
(4) reset_index(): index 0~ ์ง์ + index๋ ๋ถ๋ถ์ ์๋ก์ด column์ผ๋ก ์ง์
(5) dataframeํ ํ๊ธฐ ์ํด [[]]
(6) merge - inner merge / left_on / right_on
(7) ๋ ๋ฌธ์์ด ์ด ํฉ์น ๋ ๊ฐ ์ด astype(str) ํ์ฉํด์ ๊ฐ๊ฐ ๋ถ์ฌ ์๋ก์ด ์ด ์์ฑ
(8) nunique()์ ๊ฐ ์ด์ ๋ฐ์ดํฐ ์ค๋ณต ์ ๊ฑฐ ๊ณ ์ ๊ฐ ๊ฐ์
(9) df.shapeํ์ฉํด ์ ์ฒด ํ์ ๊ฐ์ ๋ฐ ์ด์ ๊ฐ์ ์ ์ ์์
(10) median(), quantile(0.2.5), quantile(0.75)
(11) between() ์ ์ฉํด ํน์ ์ด์ ๋ฒ์์ ๋ง๋ ๋ฐ์ดํฐ๋ง ํํฐ๋ง / sort_values(by = '์ด ์ด๋ฆ')์ผ๋ก ํน์ ์ด ๊ธฐ์ค ์ค๋ฆ/๋ด๋ฆผ์ฐจ์ / drop_duplicates() ํ์ฉํด ํน์ ์ด์ ๋ชจ์๋ง ์ค๋ณต๋ ๋ฐ์ดํฐ ์ ๊ฑฐ ๊ฐ๋ฅ
(12) .str.split()์ผ๋ก ์ด์ ๊ฐ ๋ด์ฉ์ ๋ฌธ์์ด๋ก ๋ณํํ๊ณ ๋น์นธ ๋ณ split() / apply(lambda x)๋ก if๋ฌธ์ ๋ฐ๋ผ ๋ด์ฉ ์ถ์ถ / sort_values()๋ก ๋ ๊ฐ ์ด์์ ์ด ์ ๋ ฌ ๊ฐ๋ฅ(by์ ascending ๊ฐ์ ์ ๋ ฌ ์ฐ์ ์์์ ๋ฐ๋ผ []์์ ๋ฃ์ผ๋ฉด ๋๋ค.
(13) groupby()๋ด์ ๊ทธ๋ฃนํ๋ ์ด์ ๊ฐ์๋ก groupingํ๊ณ ์ถ๋ค๋ฉด groupby('์ด ์ด๋ฆ').size()๋ก ๊ฐ๋ฅ, ์ด ๋ ๊ฐ์๋ผ๋ ์๋ก์ด ์ด์ด ๋ง๋ค์ด์ง๋ฏ๋ก reset_index()์์ name ์ธ์๋ก ์๋ก์ด ์ด ์ด๋ฆ ์ง์ ๊ฐ๋ฅ(๋๋ groupby ๊ฒฐ๊ณผ Series๋ฅผ to_frame()์ผ๋ก ๋ฐ์ดํฐํ๋ ์์ผ๋ก ๋ฐ๊พธ๋ฉด์ to_frame()์์ ์ด๋ฆ ์ค์ ๋ ๊ฐ๋ฅ)
(14) ์ด๋ค ๋ฐ์ดํฐ์ ์์ ์ด ๋ง๋ค ๋, .rank(method = 'first', ascendig = False)๋ก ์ง์ ๊ฐ๋ฅ. method = 'first'๋ ๋์ผ ์์ ์, ์ ์ด ๋จผ์ ์์ ๋ฑ์ ๋ถ์ฌ
(15) datetime filtering ๋ถ๋ฑ์ ๋๋ between() ํ์ฉ
(16) groupby์ ๋ ๊ฐ์ง ์ด์์ ์ด์ ๋ฃ์ด ๊ธฐ์ค์ผ๋ก grouping ๊ฐ๋ฅ.
(17) ๋ ์นผ๋ผ ์ฌ์ด์ ์ ๋๊ฐ์ ํ๊ท ๊ฐ ์์ฒด๋ฅผ ํ ๋ฐฉ์ ๊ตฌํ ์ ์์.
(18) 02014 ๋ฌธ์ ๋ฅผ ๋ณด๋ฉฐ groupby ๋๋ฒ์ ํ์์ฑ ๊ธฐ์ต / .dt.hour & .dt.date ํ์ฉ
'Data Science Fundamentals > Pandas&Numpy and Questions' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฅฐ StrataScratch PythonPandas Easy I - 1 Solved (0) | 2025.03.16 |
---|---|
map & applymap & apply(for dataframe & Series) (1) | 2024.06.02 |
dataframe ๊พธ๋ฏธ๊ธฐ (1) | 2023.01.22 |
Numpy fundamentals 2/2 (0) | 2023.01.16 |
pandas Tricks (Kevin by DataSchool) ์๋ฃ! COMPILATION (0) | 2022.04.18 |
๋๊ธ