잠토의 잠망경

[Pandas] DataFrame To Series 뽑아내기 본문

공부/Python

[Pandas] DataFrame To Series 뽑아내기

잠수함토끼 2018. 12. 23. 15:41

DataFrame에서 Series 추출(loc)

loc 속성을 이용하여 원하는 index를 지정후 추출

import pandas as pd

from collections import OrderedDict

s = pd.DataFrame({  'Address':['Seoul','Asan'],
                    'occupation':['doctor','IT'],
                    'Born':['1981-01-10','1999-11-02'],
                    'Died':['2100-01-10','2099-01-02'],
                    'Age':[40,20]},
                    index=['a','b'],
                    columns=['occupation', 'Born', 'Died','Age'])

print(s.loc['b'])
print(type(s.loc['b']))

output

>>> print(s.loc['b'])
occupation            IT
Born          1999-11-02
Died          2099-01-02
Age                   20
Name: b, dtype: object
>>>
>>> print(type(s.loc['b']))
<class 'pandas.core.series.Series'>

index, values, keys Method 사용하기

index - 속성
values - 속성
Keys - Method

import pandas as pd

from collections import OrderedDict

s = pd.DataFrame({  'Address':['Seoul','Asan'],
                    'occupation':['doctor','IT'],
                    'Born':['1981-01-10','1999-11-02'],
                    'Died':['2100-01-10','2099-01-02'],
                    'Age':[40,20]},
                    index=['a','b'],
                    columns=['occupation', 'Born', 'Died','Age'])

target_row = s.loc['b']

print(target_row.index)  # 'occupation', 'Born', 'Died', 'Age'
print(target_row.values) # 'IT' '1999-11-02' '2099-01-02' 20
print(target_row.keys())

output

>>> print(target_row.index)
Index([u'occupation', u'Born', u'Died', u'Age'], dtype='object')
>>> print(target_row.values)
['IT' '1999-11-02' '2099-01-02' 20]
>>> print(target_row.keys())
<bound method Series.keys of occupation            IT
Born          1999-11-02
Died          2099-01-02
Age                   20
Name: b, dtype: object>

응용

import pandas as pd

from collections import OrderedDict

s = pd.DataFrame({  'Address':['Seoul','Asan'],
                    'occupation':['doctor','IT'],
                    'Born':['1981-01-10','1999-11-02'],
                    'Died':['2100-01-10','2099-01-02'],
                    'Age':[40,20]},
                    index=['a','b'],
                    columns=['occupation', 'Born', 'Died','Age'])

target_row = s.loc['b']

print(target_row.index[0])
print(target_row.keys()[0])

output

>>> print(target_row.index[0])
occupation
>>> print(target_row.keys()[0])
occupation
Comments