728x90
반응형
In [1]:
import pandas as pd
In [2]:
# Create an example dataframe about a fictional army
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'deaths': [523, 52, 25, 616, 43, 234, 523, 62, 62, 73, 37, 35],
'battles': [5, 42, 2, 2, 4, 7, 8, 3, 4, 7, 8, 9],
'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005, 1099, 1523],
'veterans': [1, 5, 62, 26, 73, 37, 949, 48, 48, 435, 63, 345],
'readiness': [1, 2, 3, 3, 2, 1, 2, 3, 2, 1, 2, 3],
'armored': [1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1],
'deserters': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'origin': ['Arizona', 'California', 'Texas', 'Florida', 'Maine', 'Iowa', 'Alaska', 'Washington', 'Oregon', 'Wyoming', 'Louisana', 'Georgia']}
In [6]:
army = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'deaths', 'battles', 'size', 'veterans', 'readiness', 'armored', 'deserters', 'origin'])
army
Out[6]:
In [7]:
army = army.set_index('origin') # index를 기존 column인 origin으로 설정
army
Out[7]:
In [8]:
army['veterans']
Out[8]:
In [13]:
army[['veterans','deaths']]
Out[13]:
In [14]:
army.columns
Out[14]:
In [16]:
army.loc[['Marine','Alaska'],['deaths','size']]
# loc[[행],[열]]
Out[16]:
In [18]:
army.iloc[3:7,3:6]
# iloc은 숫자 인덱스로 / loc은 실제 변수 이름으로
Out[18]:
In [19]:
army.iloc[4:]
# 4 : Florida 포함 X
Out[19]:
In [20]:
army[:4]
Out[20]:
In [26]:
army.iloc[:,3:7]
# 3번째 열부터 7번째 열까지 인덱싱
Out[26]:
In [27]:
army[army['deaths'] > 50]
Out[27]:
In [30]:
army[(army['deaths'] > 500) | (army['deaths'] < 50)]
Out[30]:
In [36]:
army[army['regiment'] != 'Dragoons']
# army[(army['regiment'] != 'Dragoons')] 가능
Out[36]:
In [37]:
army.loc[['Texas','Arizona']]
Out[37]:
In [41]:
# army.columns[2] = 'deaths' 3번째 열
army.loc[['Arizona'],['deaths']]
Out[41]:
In [49]:
# army.index[2] -> 3번째 행 'Texas'
army.loc[['Texas'],['deaths']]
Out[49]:
728x90
반응형