콘텐츠로 이동

hossam.hs_util

hossam.hs_util

load_info

load_info(search=None, local=None)

메타데이터에서 사용 가능한 데이터셋 정보를 로드한다.

Parameters:

Name Type Description Default
search str

이름 필터 문자열. 포함하는 항목만 반환.

None
local str

로컬 메타데이터 경로. None이면 원격(BASE_URL) 사용.

None

Returns:

Name Type Description
DataFrame DataFrame

name, chapter, desc, url 컬럼을 갖는 테이블

Examples:

from hossam import *
info = load_info()
list(info.columns) #['name', 'chapter', 'desc', 'url']
Source code in hossam/hs_util.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def load_info(search: str | None = None, local: str | None = None) -> DataFrame:
    """메타데이터에서 사용 가능한 데이터셋 정보를 로드한다.

    Args:
        search (str, optional): 이름 필터 문자열. 포함하는 항목만 반환.
        local (str, optional): 로컬 메타데이터 경로. None이면 원격(BASE_URL) 사용.

    Returns:
        DataFrame: name, chapter, desc, url 컬럼을 갖는 테이블

    Examples:
        ```python
        from hossam import *
        info = load_info()
        list(info.columns) #['name', 'chapter', 'desc', 'url']
        ```
    """
    global BASE_URL

    path = None

    if not local:
        data_path = join(BASE_URL, "metadata.json").replace("\\", "/")

        with requests.Session() as session:
            r = session.get(data_path)

            if r.status_code != 200:
                raise Exception("[%d Error] %s ::: %s" % (r.status_code, r.reason, data_path))

        my_dict = r.json()
    else:
        data_path = join(local, "metadata.json")

        if not exists(data_path):
            raise FileNotFoundError("존재하지 않는 데이터에 대한 요청입니다.")

        with open(data_path, "r", encoding="utf-8") as f:
            my_dict = json.loads(f.read())

    my_data = []
    for key in my_dict:
        if 'index' in my_dict[key]:
            del my_dict[key]['index']

        my_dict[key]['url'] = "%s/%s" % (BASE_URL, my_dict[key]['url'])
        my_dict[key]['name'] = key

        if 'chapter' in my_dict[key]:
            my_dict[key]['chapter'] = ", ".join(my_dict[key]['chapter'])
        else:
            my_dict[key]['chapter'] = '공통'

        my_data.append(my_dict[key])

    my_df = DataFrame(my_data)
    my_df2 = my_df.reindex(columns=['name', 'chapter', 'desc', 'url'])

    if search:
        my_df2 = my_df2[my_df2['name'].str.contains(search.lower())]

    return my_df2

my_packages

my_packages()

현재 파이썬 인터프리터에 설치된 모든 패키지의 이름과 버전을 패키지 이름순으로 정렬하여 pandas DataFrame으로 반환합니다. Returns: pd.DataFrame: columns=['name', 'version']

Source code in hossam/hs_util.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def my_packages():
    """
    현재 파이썬 인터프리터에 설치된 모든 패키지의 이름과 버전을
    패키지 이름순으로 정렬하여 pandas DataFrame으로 반환합니다.
    Returns:
        pd.DataFrame: columns=['name', 'version']
    """
    pkgs = []
    for dist in distributions():
        name = dist.metadata['Name'] if 'Name' in dist.metadata else dist.name
        version = dist.version
        summary = dist.metadata.get('Summary', '')
        pkgs.append((name, version, summary))
    pkgs = sorted(pkgs, key=lambda x: x[0].lower())
    return pd.DataFrame(pkgs, columns=['name', 'version', 'summary'])

make_normalize_values

make_normalize_values(mean, std, size=100, round=2)

정규분포를 따르는 데이터를 생성한다.

Parameters:

Name Type Description Default
mean float

평균

required
std float

표준편차

required
size int

데이터 크기. Defaults to 100.

100
round int

소수점 반올림 자리수. Defaults to 2.

2

Returns:

Type Description
ndarray

np.ndarray: 정규분포를 따르는 데이터

Examples:

from hossam import *
x = hs.util.make_normalize_values(mean=0.0, std=1.0, size=100)
Source code in hossam/hs_util.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def make_normalize_values(
    mean: float, std: float, size: int = 100, round: int = 2
) -> np.ndarray:
    """정규분포를 따르는 데이터를 생성한다.

    Args:
        mean (float): 평균
        std (float): 표준편차
        size (int, optional): 데이터 크기. Defaults to 100.
        round (int, optional): 소수점 반올림 자리수. Defaults to 2.

    Returns:
        np.ndarray: 정규분포를 따르는 데이터

    Examples:
        ```python
        from hossam import *
        x = hs.util.make_normalize_values(mean=0.0, std=1.0, size=100)
        ```
    """
    p = 0.0
    x: np.ndarray = np.array([])
    attempts = 0
    max_attempts = 100  # 무한 루프 방지
    while p < 0.05 and attempts < max_attempts:
        x = np.random.normal(mean, std, size).round(round)
        _, p = normaltest(x)
        attempts += 1

    return x

make_normalize_data

make_normalize_data(
    means=None, stds=None, sizes=None, rounds=2
)

정규분포를 따르는 데이터프레임을 생성한다.

Parameters:

Name Type Description Default
means list

평균 목록. Defaults to [0, 0, 0].

None
stds list

표준편차 목록. Defaults to [1, 1, 1].

None
sizes list

데이터 크기 목록. Defaults to [100, 100, 100].

None
rounds int

반올림 자리수. Defaults to 2.

2

Returns:

Name Type Description
DataFrame DataFrame

정규분포를 따르는 데이터프레임

Source code in hossam/hs_util.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
def make_normalize_data(
    means: list | None = None,
    stds: list | None = None,
    sizes: list | None = None,
    rounds: int = 2,
) -> DataFrame:
    """정규분포를 따르는 데이터프레임을 생성한다.

    Args:
        means (list, optional): 평균 목록. Defaults to [0, 0, 0].
        stds (list, optional): 표준편차 목록. Defaults to [1, 1, 1].
        sizes (list, optional): 데이터 크기 목록. Defaults to [100, 100, 100].
        rounds (int, optional): 반올림 자리수. Defaults to 2.

    Returns:
        DataFrame: 정규분포를 따르는 데이터프레임
    """
    means = means if means is not None else [0, 0, 0]
    stds = stds if stds is not None else [1, 1, 1]
    sizes = sizes if sizes is not None else [100, 100, 100]

    if not (len(means) == len(stds) == len(sizes)):
        raise ValueError("means, stds, sizes 길이는 동일해야 합니다.")

    data = {}
    for i in range(len(means)):
        data[f"X{i+1}"] = make_normalize_values(
            means[i], stds[i], sizes[i], rounds
        )

    return DataFrame(data)

pretty_table

pretty_table(data, tablefmt='simple', headers='keys')

tabulate를 사용해 DataFrame을 단순 표 형태로 출력한다.

Parameters:

Name Type Description Default
data DataFrame

출력할 데이터프레임

required
tablefmt str

tabulate 테이블 포맷. Defaults to "simple".

'simple'
headers str | list

헤더 지정 방식. Defaults to "keys".

'keys'

Returns:

Type Description
None

None

Examples:

from hossam import *
from pandas import DataFrame
hs_util.pretty_table(DataFrame({"a":[1,2],"b":[3,4]}))
Source code in hossam/hs_util.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def pretty_table(data: DataFrame, tablefmt="simple", headers: str = "keys") -> None:
    """`tabulate`를 사용해 DataFrame을 단순 표 형태로 출력한다.

    Args:
        data (DataFrame): 출력할 데이터프레임
        tablefmt (str, optional): `tabulate` 테이블 포맷. Defaults to "simple".
        headers (str | list, optional): 헤더 지정 방식. Defaults to "keys".

    Returns:
        None

    Examples:
        ```python
        from hossam import *
        from pandas import DataFrame
        hs_util.pretty_table(DataFrame({"a":[1,2],"b":[3,4]}))
        ```
    """

    tabulate.WIDE_CHARS_MODE = False # type: ignore
    print(
        tabulate(data, headers=headers, tablefmt=tablefmt, showindex=True, numalign="right") # type: ignore
    )

load_data

load_data(
    key,
    index_col=None,
    timeindex=False,
    info=True,
    categories=None,
    local=None,
)

데이터 키를 통해 데이터를 로드한 뒤 기본 전처리/출력을 수행한다.

Parameters:

Name Type Description Default
key str

데이터 키 (metadata.json에 정의된 데이터 식별자)

required
index_col str

인덱스로 설정할 컬럼명. Defaults to None.

None
timeindex bool

True일 경우 인덱스를 시계열(DatetimeIndex)로 설정한다. Defaults to False.

False
info bool

True일 경우 데이터 정보(head, tail, 기술통계, 카테고리 정보)를 출력한다. Defaults to True.

True
categories list

카테고리 dtype으로 설정할 컬럼명 목록. Defaults to None.

None
local str

원격 데이터 대신 로컬 메타데이터 경로를 사용한다. Defaults to None.

None

Returns:

Name Type Description
DataFrame DataFrame

전처리(인덱스 설정, 카테고리 변환)가 완료된 데이터프레임

Examples:

from hossam import *
df = hs_util.load_data("AD_SALES", index_col=None, timeindex=False, info=False)
Source code in hossam/hs_util.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def load_data(key: str,
                index_col: str | None = None,
                timeindex: bool = False,
                info: bool = True,
                categories: list | None = None,
                local: str | None = None) -> DataFrame:
    """데이터 키를 통해 데이터를 로드한 뒤 기본 전처리/출력을 수행한다.

    Args:
        key (str): 데이터 키 (metadata.json에 정의된 데이터 식별자)
        index_col (str, optional): 인덱스로 설정할 컬럼명. Defaults to None.
        timeindex (bool, optional): True일 경우 인덱스를 시계열(DatetimeIndex)로 설정한다. Defaults to False.
        info (bool, optional): True일 경우 데이터 정보(head, tail, 기술통계, 카테고리 정보)를 출력한다. Defaults to True.
        categories (list, optional): 카테고리 dtype으로 설정할 컬럼명 목록. Defaults to None.
        local (str, optional): 원격 데이터 대신 로컬 메타데이터 경로를 사용한다. Defaults to None.

    Returns:
        DataFrame: 전처리(인덱스 설정, 카테고리 변환)가 완료된 데이터프레임

    Examples:
        ```python
        from hossam import *
        df = hs_util.load_data("AD_SALES", index_col=None, timeindex=False, info=False)
        ```
    """

    k = key.lower()

    origin = None

    if k.endswith(".xlsx"):
        origin = read_excel(key)
    elif k.endswith(".csv"):
        origin = read_csv(key)
    else:
        origin = _load_data_remote(key, local) # type: ignore

    if origin is None:
        raise RuntimeError("Data loading failed: origin is None")

    return __data_info(origin, index_col, timeindex, info, categories)

is_2d

is_2d(x)

주어진 객체가 2차원 리스트인지 확인합니다.

Parameters:

Name Type Description Default
x

확인할 객체

required

Returns:

Name Type Description
bool bool

객체가 2차원 리스트인 경우 True, 그렇지 않은 경우 False

Source code in hossam/hs_util.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def is_2d(x) -> bool:
    """
    주어진 객체가 2차원 리스트인지 확인합니다.

    Args:
        x: 확인할 객체

    Returns:
        bool: 객체가 2차원 리스트인 경우 True, 그렇지 않은 경우 False
    """
    return (
        isinstance(x, (list, tuple)) and
        len(x) > 0 and
        all(isinstance(i, (list, tuple)) for i in x)
    )