2022/01/10/MON
import matplotlib.pyplot as plt
from plotnine import *
import numpy as np
import pandas as pd
np.random.seed(1)
df=pd.DataFrame(np.random.normal(size=(15,4)),columns=list('ABCD'))
df.query('A>0 & B<0')
df.query('A>0 and B<0')
- lambda 사용할 때 &로 묶을 땐 and와의 차이점이 있었는데 query에선 없는 것 같음
df.query('A<B<C')
df.A.mean()
df['A'].mean()
df.query('A>-0.018839420539994597')
meanA=df.A.mean()
df.query('A> @meanA')
#`@meanA` 대신 `@df.A.mean()` 가능
df.query(' A> @meanA and A<0.8')
df.query('index==0 or 3 <= index <=5 or 9<=index <=11')
df.query('index==0 or index ==[8,9,10]')
i1= np.arange(3) # 0,1,2를 의미
df.query('index in @i1 or index==5')
df2=pd.DataFrame(np.random.normal(size=(10,4)), columns=list('ABCD'),
index=pd.date_range('20201226',periods=10))
df2
df2.query('"2020-12-27"<= index <= "2021-01-03"')
df2.query(' "2020-12-27"<= index <= "2021-01-03" and A+B < C')
fifa22=pd.read_csv('https://raw.githubusercontent.com/guebin/2021DV/master/_notebooks/2021-10-25-FIFA22_official_data.csv')
fifa22.sort_values(by='Overall',ascending=False).head(2)
fifa22.sort_values(by='Overall',ascending=False).reset_index()
fifa22=fifa22.sort_values(by='Overall',ascending=False).reset_index().rename(columns={'index':'index_old'})
# Overall 기준 정렬 // ascending=False -> 내림차순 (디폴트 = 오름차순)
# reset_index().rename(columns={'index':'index_old'}) -> 인덱스 초기화하고 index -> index_old
ggplot(fifa22)+geom_point(aes(x='Overall', y='Potential'),alpha=0.1)
fifa22['Potential2'] = fifa22['Potential'] - fifa22['Overall']
ggplot(fifa22)+geom_point(aes(x='Overall', y='Potential2'),alpha=0.1,position='jitter')
ggplot(fifa22.query('Potential2>0.1'))+geom_point(aes(x='Overall', y='Potential2'),alpha=0.1,position='jitter')
fifa22.Overall.hist()
def f(x):
if x>72: y='Q1'
elif x>68: y='Q2'
elif x>63: y='Q3'
else: y='Q4'
return y
fifa22['Q']=list(map(f,fifa22.Overall))
ggplot(fifa22.query('Potential2>0.1'))\
+geom_boxplot(aes(x='Q',y='Potential2'))
fifa22.groupby(by='Q').mean()
fifa22.groupby(by='Q').mean().Overall # Q1,Q2,Q3,Q4의 Overall평균만, 현재 자료형은 float
l_=fifa22.groupby(by='Q').mean().Overall
type(l_)
l_은 pandas series형태
l=fifa22.groupby(by='Q').mean().Overall.to_list() # to_list() 해당 자료를 list로 만들겠다
l
- 이제 박스플랏이 들어갈 x축의 위치를 저장할 컬럼을 추가하고 그 이름을 Qx 라고 하자.
def g(x):
if x=='Q1': y=l[0]
elif x=='Q2': y=l[1]
elif x=='Q3': y=l[2]
else: y=l[3]
return y
fifa22['Qx']=list(map(g,fifa22.Q))
ggplot(fifa22.query('Potential2>0.1'))\
+geom_point(aes(x='Overall', y='Potential2',color='Q'),alpha=0.1,size=0.1,position='jitter')\
+geom_boxplot(aes(x='Qx', y='Potential2',color='Q')) # 박스플랏이 overall 평균에 위치可
fifa22.query('Q=="Q1" and Potential2>20')