Lobo's code station/빅데이터

컬럼중 속성에 해당하는 컬럼 반환

Lobo 2024. 6. 12. 10:53

Isinstance(value,속성)
Timestamp로만 적을경우 not defined 오류 발생
따라서 pd.로 판다스에서 해당 속성을 가져올것임을 명시
해당하지 않는 것을 찾으려면 not isinstance 사용

import pandas as pd

# 예시 데이터프레임 생성
data = {
    'col1': [(1, 'a'), (2, 'b')],  # 숫자와 문자열이 포함된 튜플
    'col2': [('x', 'y'), ('z', 'w')],  # 문자열만 포함된 튜플
    'col3': [('apple', 'banana'), ('cat', 'dog')],  # 문자열만 포함된 튜플
    'col4': [pd.Timestamp('2022-01-01'), pd.Timestamp('2023-01-01')],  # Timestamp만 포함
    'col5': ['foo', 'bar']  # 문자열만 포함
}
df = pd.DataFrame(data)

# 숫자 또는 Timestamp가 아닌 값을 포함하는 열을 찾는 함수
def find_columns_with_only_timestamps_or_non_numeric(df):
    non_numeric_cols = []
    for col in df.columns:
        if all(
            isinstance(value, pd.Timestamp) or  # 값이 Timestamp인 경우
            not isinstance(value, (int, float))  # 값이 숫자가 아닌 경우
            for value in df[col]
        ):
            non_numeric_cols.append(col)  # 조건을 만족하는 열 이름을 리스트에 추가
    return non_numeric_cols

# 함수 실행
non_numeric_columns = find_columns_with_only_timestamps_or_non_numeric(df)
print("숫자가 포함되지 않은 열 (Timestamp 포함):", non_numeric_columns)