언패킹 연산자 *
와 **
는 파이썬에서 반복 가능한 객체(리스트, 튜플, 딕셔너리)의 요소를 풀어서 함수의 인자로 전달하거나, 새로운 변수에 할당하는 역할을 한다.
*
연산자def my_function(a, b, c):
print(a, b, c)
args = [1, 2, 3]
my_function(*args) # my_function(1, 2, 3)과 동일하게 동작
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = [*list1, *list2]
print(combined_list) # [1, 2, 3, 4, 5, 6]
**
연산자def my_funtion(a, b, c):
print(a, b, c)
kwargs = {'a': 1, 'b': 2, 'c': 3}
my_funcrion(**kwargs) # my_function(a=1, b=2, c=3)과 동일하게 동작
# output= 1, 2, 3
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dict = {**dict1, **dict2}
print(combined_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
EDA(Exploratory Data Analysis)과정에서 테이블 구조를 살펴보고 싶을 때 describe()
,columns()
메서드, shape
,columns
,dtypes
속성 등을 사용한다.
이 때 복수의 테이블에 대한 정보를 한번에 출력하고 싶은 경우 for반복문을 사용할 수 있다.
예를 들어 DataFrame1
, DataFrame2
, DataFrame3
, DataFrame4
이 있다고 치자.
모든 dataframe에 columns속성을 사용하는 for반복문 만들기
# columns() 반복문 def print_all_columns(*dataframes): for i, df in enumerate(dataframes): print(f"DataFrame {i+1}") print(df.columns.tolist()) print("\n" + "="*50 + "\n")
위 구조에서 *dataframes
를 통해 복수의 데이터프레임을 print_all_columns함수의 인자로 받아올 수 있다.
print_all_columns(DataFrame1
,DataFrame2
,DataFrame3
,DataFrame4
)
DataFrame1
,DataFrame2
,DataFrame3
,DataFrame4
) 함수 실행 결과