pandas

[pandas] Data Frame 생성 방법

전감자(◔◡◔) 2022. 10. 2. 15:07

1. Pandas 함수 확인

Data Frame 을 생성하는 법을 배우기 이전에 dir() 을 이용하여

pandas 안에 어떠한 함수들이 존재하는지부터 확인!

 

import numpy as np
import pandas as pd

print(dir(pd))
'''
pd 함수
['ArrowDtype', 'BooleanDtype', 'Categorical', 'CategoricalDtype', 'CategoricalIndex', 
'DataFrame', 'DateOffset', 'DatetimeIndex', 'DatetimeTZDtype', 'ExcelFile', 'ExcelWriter', 
'Flags', 'Float32Dtype', 'Float64Dtype', 'Float64Index', 'Grouper', 'HDFStore', 'Index', 
'IndexSlice', 'Int16Dtype', 'Int32Dtype', 'Int64Dtype', 'Int64Index', 'Int8Dtype', 'Interval', 
'IntervalDtype', 'IntervalIndex', 'MultiIndex', 'NA', 'NaT', 'NamedAgg', 'Period', 'PeriodDtype', 
'PeriodIndex', 'RangeIndex', 'Series', 'SparseDtype', 'StringDtype', 'Timedelta', 'TimedeltaIndex', 
'Timestamp', 'UInt16Dtype', 'UInt32Dtype', 'UInt64Dtype', 'UInt64Index', 'UInt8Dtype', 
'__all__', '__builtins__', '__cached__', '__deprecated_num_index_names', '__dir__', '__doc__', 
'__docformat__', '__file__', '__getattr__', '__git_version__', '__loader__', '__name__', 
'__package__', '__path__', '__spec__', '__version__', '_config', '_is_numpy_dev', '_libs', 
'_testing', '_typing', '_version', 
'annotations', 'api', 'array', 'arrays', 'bdate_range', 
'compat', 'concat', 'core', 'crosstab', 'cut', 'date_range', 'describe_option', 'errors', 
'eval', 'factorize', 'from_dummies', 'get_dummies', 'get_option', 'infer_freq', 'interval_range', 
'io', 'isna', 'isnull', 'json_normalize', 'lreshape', 'melt', 'merge', 'merge_asof', 'merge_ordered', 
'notna', 'notnull', 'offsets', 'option_context', 'options', 'pandas', 'period_range', 'pivot', 
'pivot_table', 'plotting', 'qcut', 'read_clipboard', 'read_csv', 'read_excel', 'read_feather', 
'read_fwf', 'read_gbq', 'read_hdf', 'read_html', 'read_json', 'read_orc', 'read_parquet', 'read_pickle', 
'read_sas', 'read_spss', 'read_sql', 'read_sql_query', 'read_sql_table', 'read_stata', 'read_table', 
'read_xml', 'reset_option', 'set_eng_float_format', 'set_option', 'show_versions', 'test', 'testing', 
'timedelta_range', 'to_datetime', 'to_numeric', 'to_pickle', 'to_timedelta', 'tseries', 'unique', 
'util', 'value_counts', 'wide_to_long']
'''

'''
df 함수
['T', '_AXIS_LEN', '_AXIS_ORDERS', '_AXIS_TO_AXIS_NUMBER', '_HANDLED_TYPES', 
'__abs__', '__add__', '__and__', '__annotations__', '__array__', '__array_priority__', 
'__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__contains__', '__copy__', 
'__dataframe__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', 
'__divmod__', '__doc__', '__eq__', '__finalize__', '__floordiv__', '__format__', '__ge__', 
'__getattr__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', 
'__iadd__', '__iand__', '__ifloordiv__', '__imod__', '__imul__', '__init__', '__init_subclass__', 
'__invert__', '__ior__', '__ipow__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', 
'__len__', '__lt__', '__matmul__', '__mod__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', 
'__nonzero__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rfloordiv__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', 
'__round__', '__rpow__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', 
'__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', 
'__xor__', '_accessors', '_accum_func', '_add_numeric_operations', '_agg_by_level', '_agg_examples_doc', 
'_agg_summary_and_see_also_doc', '_align_frame', '_align_series', '_append', '_arith_method', 
'_as_manager', '_attrs', '_box_col_values', '_can_fast_transpose', 
'_check_inplace_and_allows_duplicate_labels', '_check_inplace_setting', 
'_check_is_chained_assignment_possible', '_check_label_or_level_ambiguity', '_check_setitem_copy', 
'_clear_item_cache', '_clip_with_one_bound', '_clip_with_scalar', '_cmp_method', '_combine_frame', 
'_consolidate', '_consolidate_inplace', '_construct_axes_dict', '_construct_axes_from_arguments', 
'_construct_result', '_constructor', '_constructor_sliced', '_convert', '_count_level', '_data', 
'_dir_additions', '_dir_deletions', '_dispatch_frame_op', '_drop_axis', '_drop_labels_or_levels', 
'_ensure_valid_index', '_find_valid_index', '_flags', '_from_arrays', '_get_agg_axis', '_get_axis', 
'_get_axis_name', '_get_axis_number', '_get_axis_resolvers', '_get_block_manager_axis', 
'_get_bool_data', '_get_cleaned_column_resolvers', '_get_column_array', '_get_index_resolvers', 
'_get_item_cache', '_get_label_or_level_values', '_get_numeric_data', '_get_value', 
'_getitem_bool_array', '_getitem_multilevel', '_gotitem', '_hidden_attrs', '_indexed_same', 
'_info_axis', '_info_axis_name', '_info_axis_number', '_info_repr', '_init_mgr', '_inplace_method', 
'_internal_names', '_internal_names_set', '_is_copy', '_is_homogeneous_type', 
'_is_label_or_level_reference', '_is_label_reference', '_is_level_reference', '_is_mixed_type', '_is_view', 
'_iset_item', '_iset_item_mgr', '_iset_not_inplace', '_item_cache', '_iter_column_arrays', '_ixs', '_join_compat', 
'_logical_func', '_logical_method', '_maybe_cache_changed', '_maybe_update_cacher', '_metadata', '_mgr', 
'_min_count_stat_function', '_needs_reindex_multi', '_protect_consolidate', '_reduce', '_reduce_axis1', '_reindex_axes', 
'_reindex_columns', '_reindex_index', '_reindex_multi', '_reindex_with_indexers', '_rename', '_replace_columnwise', 
'_repr_data_resource_', '_repr_fits_horizontal_', '_repr_fits_vertical_', '_repr_html_', '_repr_latex_', '_reset_cache', 
'_reset_cacher', '_sanitize_column', '_series', '_set_axis', '_set_axis_name', '_set_axis_nocheck', '_set_is_copy', 
'_set_item', '_set_item_frame_value', '_set_item_mgr', '_set_value', '_setitem_array', '_setitem_frame', '_setitem_slice', 
'_slice', '_stat_axis', '_stat_axis_name', '_stat_axis_number', '_stat_function', '_stat_function_ddof', '_take', 
'_take_with_is_copy', '_to_dict_of_blocks', '_typ', '_update_inplace', '_validate_dtype', '_values', '_where', 
'abs', 'add', 'add_prefix', 'add_suffix', 'agg', 'aggregate', 'align', 'all', 'any', 'append', 'apply', 
'applymap', 'asfreq', 'asof', 'assign', 'astype', 'at', 'at_time', 'attrs', 'axes', 'backfill', 'between_time', 
'bfill', 'bool', 'boxplot', 'c1', 'c2', 'c3', 'clip', 'columns', 'combine', 'combine_first', 'compare', 'convert_dtypes', 
'copy', 'corr', 'corrwith', 'count', 'cov', 'cummax', 'cummin', 'cumprod', 'cumsum', 'describe', 'diff', 'div', 'divide', 
'dot', 'drop', 'drop_duplicates', 'droplevel', 'dropna', 'dtypes', 'duplicated', 'empty', 'eq', 'equals', 'eval', 'ewm', 
'expanding', 'explode', 'ffill', 'fillna', 'filter', 'first', 'first_valid_index', 'flags', 'floordiv', 'from_dict', 
'from_records', 'ge', 'get', 'groupby', 'gt', 'head', 'hist', 'iat', 'idxmax', 'idxmin', 'iloc', 'index', 'infer_objects', 
'info', 'insert', 'interpolate', 'isetitem', 'isin', 'isna', 'isnull', 'items', 'iteritems', 'iterrows', 'itertuples', 'join', 
'keys', 'kurt', 'kurtosis', 'last', 'last_valid_index', 'le', 'loc', 'lookup', 'lt', 'mad', 'mask', 'max', 'mean', 'median', 
'melt', 'memory_usage', 'merge', 'min', 'mod', 'mode', 'mul', 'multiply', 'ndim', 'ne', 'nlargest', 'notna', 'notnull', 
'nsmallest', 'nunique', 'pad', 'pct_change', 'pipe', 'pivot', 'pivot_table', 'plot', 'pop', 'pow', 'prod', 'product', 
'quantile', 'query', 'radd', 'rank', 'rdiv', 'reindex', 'reindex_like', 'rename', 'rename_axis', 'reorder_levels', 
'replace', 'resample', 'reset_index', 'rfloordiv', 'rmod', 'rmul', 'rolling', 'round', 'rpow', 'rsub', 'rtruediv', 
'sample', 'select_dtypes', 'sem', 'set_axis', 'set_flags', 'set_index', 'shape', 'shift', 'size', 'skew', 'slice_shift', 
'sort_index', 'sort_values', 'squeeze', 'stack', 'std', 'style', 'sub', 'subtract', 'sum', 'swapaxes', 'swaplevel', 'tail', 
'take', 'to_clipboard', 'to_csv', 'to_dict', 'to_excel', 'to_feather', 'to_gbq', 'to_hdf', 'to_html', 'to_json', 'to_latex', 
'to_markdown', 'to_numpy', 'to_orc', 'to_parquet', 'to_period', 'to_pickle', 'to_records', 'to_sql', 'to_stata', 'to_string', 
'to_timestamp', 'to_xarray', 'to_xml', 'transform', 'transpose', 'truediv', 'truncate', 'tz_convert', 'tz_localize', 'unstack', 
'update', 'value_counts', 'values', 'var', 'where', 'xs']
'''

 

진짜 엄청나게 많은 함수가 존재하는 것을 확인할 수 있다 ㄷㄷ

당연히 저걸 다 외워야할 필요가 있는 것은 아니지만 유용하게 쓰일 때가 있으니 파일에 주석으로 달아 두고

어떤 함수가 존재하는지 한 번씩 확인하도록 하자 -! 

 

 

 

2. Data Frame 생성 방법

# 1.  dict 이용
dict_value = {"c1":[4,5,6],
              "c2":[14,35,26],
              "c3":[43,50,61]}

df = pd.DataFrame(dict_value)
print(df, type(df)) # <class 'pandas.core.frame.DataFrame'>
'''
   c1  c2  c3
0   4  14  43
1   5  35  50
2   6  26  61
'''

 

Pandas 를 이용하여 DataFrame 을 생성하는 법을 알아보자 

Data Frame 은 우리가 잘 알고있는 형태인 Dict 형태로 만들 수 가 있는데 ,

이 때 key 값이 컬럼 값 , 즉 열이 되고 value 값이 열에 한 줄로 들어가는 것을 확인 할 수 있다. 

이 때 행 방향으로 0,1,2 라는 값이 붙은 것이 보이는데
이는 자동으로 붙는 인덱스 값이다. 

 

 

3. 컬럼 순서 변경

# 2. 원하는 컬럼순서 변경
dict_value = {"c1":[4,5,6],
              "c2":[14,35,26],
              "c3":[43,50,61]}

df = pd.DataFrame(dict_value, columns=['c2','c1','c3'])
print(df)
'''
   c2  c1  c3
0  14   4  43
1  35   5  50
2  26   6  61
'''

 

DataFrame( ) 함수에 있는 columns 속성을 이용해서 컬럼 순서를 변경하는 것이 가능하다. 

단순히 컬럼의 이름만 바뀌는 것이 아니라 각 열에 있는 값까지 통째로 바뀐다는 점을 주의하자 . 

 

 

4. 중첩 리스트 OR 2차원 리스트로 생성하기 

 

'''
     df = pd.DataFrame(중첩리스트|2차원배열, columns=[], index=[] )
    ==>   2차원배열을 만드는 방법으로 DataFrame 생성이 가능하다.
'''

 

DataFrame() 에 딕셔너리가 아닌 중첩 리스트 또는 numpy array 를 넣어서 DataFrame 을 만들 수 있다. 

 

list_value = [[4,5,6],[1,2,3],[7,5,3]] # list
arr = np.array([[4,5,6],[1,2,3],[7,5,3]]) # ndarray

df = pd.DataFrame(list_value, columns=['a','b','c'])
df = pd.DataFrame(arr, columns=['a','b','c'])
print(df)
'''
   a  b  c
0  4  5  6
1  1  2  3
2  7  5  3
'''

df = pd.DataFrame(list_value, index=[10,20,30], columns=['a','b','c'])
df = pd.DataFrame(arr, index=['r1','r2','r3'],columns=['a','b','c'])
print(df)
'''
 a  b  c
r1  4  5  6
r2  1  2  3
r3  7  5  3
'''
d1 = np.arange(12).reshape(3,4)
df = pd.DataFrame(d1, columns=['A','B','C','D'])
print(df)
'''
   A  B   C   D
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
'''

 

 

5. 랜덤함수로 생성하기 

numpy 랜덤함수들 이용해서 ndarray 를 생성하고 Data Frame m으로 변경 

-1.np.random.random([(행,열)])  => [0.0,1.0) 

print("1. np.random.random()")
df = pd.DataFrame(np.random.random((2,3)), columns=list("ABC"))
print(df)
'''
          A         B         C
0  0.510716  0.088186  0.963765
1  0.288950  0.827463  0.629649
'''

 

-2. np.random.rand((행,열))  => [0.0,1.0) 균등 분포 추출

print("2. np.random.rand([갯수])")
df = pd.DataFrame(np.random.rand(2,3), columns=list("ABC"))
print(df)
'''
        A         B         C
0  0.64528  0.108438  0.242832
1  0.47977  0.369909  0.059353
'''

 

 

 

 

-3. np.random.randn(행,열)  => [0.0,1.0) 정규 분포 추출

print("3. np.random.randn([갯수])")
df = pd.DataFrame(np.random.randn(2,3), columns=list("ABC"))
print(df)
'''
         A         B         C
0 -1.122875  1.139383  0.839084
1  0.217829 -0.568051  0.960992
'''

 

-4. np.random.randint(a,b,size)  =>  [a=0,b) 사이 정수 랜덤 추출 

print("4. np.random.randint([갯수])")
df = pd.DataFrame(np.random.randint(2, size=(2,3)), columns=list("ABC"))
print(df)
'''
   A  B  C
0  1  0  1
1  1  1  1
'''

 

-5. np.random.choice(리스트,size=(행,열))  => 주어진 리스트에서 랜덤 추출

print("5. np.random.choice(리스트, size=(2,3))")
df = pd.DataFrame(np.random.choice([3,6,8,9], size=(2,3)), columns=list("ABC"))
print(df)
'''
   A  B  C
0  8  9  6
1  8  8  8

'''

 

6. Series 생성 

한 줄씩 생성해서 리스트에 담은 다음 DataFrame 생성

s1 = pd.Series([10,20,30],name="age")
print(s1, type(s1)) # <class 'pandas.core.series.Series'>
'''
0    10
1    20
2    30
Name: age, dtype: int64
'''
s2 = pd.Series(["홍길동","이순신","강감찬"],name="username")
print(s2)
'''
0    홍길동
1    이순신
2    강감찬
Name: username, dtype: object
'''

df = pd.DataFrame([s1, s2])
print(df)
'''
            0    1    2
age        10   20   30
username  홍길동  이순신  강감찬
'''
print(df.T)
'''
  age username
0  10      홍길동
1  20      이순신
2  30      강감찬
'''

 

series => DataFrame

s1 = pd.Series([10,20,30],name="age")
print(s1, type(s1)) # <class 'pandas.core.series.Series'>
'''
0    10
1    20
2    30
Name: age, dtype: int64
'''

# Series ==> df 변경
df = s1.to_frame("나이")
print(df)
'''
   나이
0  10
1  20
2  30
'''

 

요약 정리

 

'''
  DataFrame 생성
  1. dict 이용
    df = pd.DataFrame({key:값,key:값})
    ==> 기본적으로 원본 dict 순서로 보여진다.
  2. 원하는 컬럼 순서 변경
  df = pd.DataFrame({key:값,key:값}, columns=['컬럼명','컬럼명','컬럼명'])
  3. 중첩 리스트
     df = pd.DataFrame(중첩리스트|2차원배열, columns=[] )
     df = pd.DataFrame(중첩리스트|2차원배열, columns=[], index=[] )
    ==>   2차원배열을 만드는 방법으로 DataFrame 생성이 가능하다.
  4. 랜덤함수 이용한 중첩리스트
  5. Series 이용
     가. Series 생성
       s1 = pd.Series()
       s2 = pd.Series()
     나. DataFrame 생성
       df = pd.DataFrame([s1,s2,....])
'''